﻿using System;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraTab;
using DevExpress.XtraTab.ViewInfo;
using Ch.Elca.Iiop;
using System.Runtime.Remoting.Channels;
using Ch.Elca.Iiop.Services;
using omg.org.CosNaming;
using BusinessLogic;
using Model;
using Model.CustomDataType;
using QlpmClient.Utils;
using DevExpress.XtraGrid.Columns;
using Model.Medicine;
using System.Threading;
using System.Data;
using QlpmClient.Report;
using DevExpress.XtraReports.UI;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraReports.Parameters;



namespace QlpmClient
{
    public partial class MainForm : RibbonForm
    {
        private NamingContext nc;
        private MyQueryBL myQueryBL;
        private PatientBL patientBL;
        private WorkerBL workerBl;
        private PositionBL positionBl;
        private TreatmentBL treatmentBL;
        private MedicineBL medicineBL;
        private PrescriptionBL prescriptionBL;
        private CMDateTime dt;
        //Khai báo các biến
        MessageboxCustom message;
        Series seriesDoanhThu = new Series("Doanh thu", ViewType.Line);
        ultils ul;

        private TreatmentFunction Kb;
        private PrescriptionformFunction Tm;
        private ConvertData data;
        private DataTable dtTrieuChung;
        private DataTable dtChuanDoan;
        private DataTable dtLoiDan;
        private DataTable dtCachDung;
        private int maxCachDung = 0;

        public MainForm()
        {
            InitializeComponent();
            InitSkinGallery();
            message = new MessageboxCustom();
            ul = new ultils();
            try
            {
                Connect();
                myQueryBL = (MyQueryBL)nc.resolve(getNamComponent("MyQueryBL"));
                patientBL = (PatientBL)nc.resolve(getNamComponent("PatientBL"));
                workerBl = (WorkerBL)nc.resolve(getNamComponent("WorkerBL"));
                positionBl = (PositionBL)nc.resolve(getNamComponent("PositionBL"));
                treatmentBL = (TreatmentBL)nc.resolve(getNamComponent("TreatmentBL"));
                medicineBL = (MedicineBL)nc.resolve(getNamComponent("MedicineBL"));
                prescriptionBL = (PrescriptionBL)nc.resolve(getNamComponent("PrescriptionBL"));
            }
            catch (Exception)
            {
                message.title = "Lỗi kết nối";
                message.Content = "Server chưa được khởi chạy";
                message.ShowDialog();
                //this.Dispose();
            }


            chartDoanhThu.Series.Add(seriesDoanhThu);
            data = new ConvertData();

            Kb = new TreatmentFunction();
            Tm = new PrescriptionformFunction();
            dtTrieuChung = new DataTable();
            dtChuanDoan = new DataTable();
            dtLoiDan = new DataTable();
            dtCachDung = new DataTable();

           
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        public void Connect()
        {
            string localhost = "localhost";
            int port = 6969;
            IiopClientChannel c = new IiopClientChannel();
            ChannelServices.RegisterChannel(c, false);
            CorbaInit ci = CorbaInit.GetInit();
            nc = ci.GetNameService(localhost, port);
        }
        public NameComponent[] getNamComponent(String name)
        {
            return new NameComponent[] { new NameComponent(name, "") };
        }

        void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }


        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// //*****************************************************************Bắt đầu tab đăng nhập*********************************************************************//
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void btnDangNhap_Click(object sender, EventArgs e)
        {
            if (txtTaiKhoan.Text.Equals("") || txtMatKhau.Text.Equals(""))
            {
                message.title = "Lỗi";
                message.Content = "Vui lòng nhập đầy đủ thông tin";
                message.ShowDialog();
                return;
            }
            try
            {

                if (!workerBl.checkLogin(txtTaiKhoan.Text, txtMatKhau.Text))
                {
                    message.title = "Lỗi";
                    message.Content = "Tài khoản hoặc mật khẩu không hợp lệ";
                    message.ShowDialog();
                    return;
                }

                string query = "select status,fullname from worker where username = N'" + txtTaiKhoan.Text + "' and password = N'" + txtMatKhau.Text + "'";
                string[] values = myQueryBL.doQuery(query);
                string[] row = values[0].Split(new string[] { "<<_>>" }, StringSplitOptions.None);
                short status = (short)Int32.Parse(row[0]);
                if (status == 0)
                {
                    message.title = "Lỗi";
                    message.Content = "Tài khoàn không có quyền đăng nhập";
                    message.ShowDialog();
                    return;
                }

                grCtrlFormDangNhap.Visible = false;
                if (row[1].Equals(""))
                    barStaticItem.Caption = "";
                else
                    barStaticItem.Caption = "Nhân viên: " + row[1];
                BarMenu.Enabled = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }




        }
        private void txtTaiKhoan_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnDangNhap_Click(sender, e);
        }

        private void txtMatKhau_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnDangNhap_Click(sender, e);
        }



        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// //*****************************************************************Kết thúc tab đăng nhập*********************************************************************//
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// //*****************************************************************Bắt đầu tab tiếp nhận*********************************************************************//
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        public void LoadAllPatient()
        {
            string query = "select TREATMENT.patientid,fullname,idcard,sex,dateofbirth,address,phonenumber,relative from PATIENT inner join TREATMENT on " +
                            " TREATMENT.patientid = PATIENT.patientid ";
            string[] str = myQueryBL.doQuery(query);
            if (str.Length > 0)
            {
                GridViewPatient.GridControl.DataSource = data.DataTablePatient(str);
            }
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            dateEdit_NgayKham.Text = "";
            dateofTreatment.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            dateofTreatment.Properties.DisplayFormat.FormatString = "dd/MM/yyyy";
            string _ngaykhambenh_timkiem = "";
            if (!dateofTreatment.Text.Equals(""))
            {
                string day = ul.SplitDay(dateofTreatment.Text);
                string month = ul.SplitMonth(dateofTreatment.Text);
                string year = ul.SplitYear(dateofTreatment.Text);
                _ngaykhambenh_timkiem = year + "/" + month + "/" + day;
            }



            if (txtTiepNhan_MaSoTimKiem.Text.Equals("") && txtTiepNhan_HoTenTimKiem.Text.Equals("") && txtTiepNhan_NamSinhTimKiem.Text.Equals("")
                && (sex.Equals("") || sex.Equals("3")) && txtTiepNhan_CMNDTimKiem.Text.Equals("") && _ngaykhambenh_timkiem.Equals(""))
            {
                message.title = "Lỗi";
                message.Content = "Vui lòng nhập thông tin để tìm kiếm";
                message.ShowDialog();
                return;
            }
            String query = "";
            string SqlMaBenhNhan;
            if (!txtTiepNhan_MaSoTimKiem.Text.Equals(""))
                SqlMaBenhNhan = " and TREATMENT.patientid = " + Int32.Parse(txtTiepNhan_MaSoTimKiem.Text.Trim());
            else
                SqlMaBenhNhan = "";
            string Sqlfullname = "";
            if (!txtTiepNhan_HoTenTimKiem.Text.Equals(""))
                Sqlfullname = " and fullname like N'%" + txtTiepNhan_HoTenTimKiem.Text + "%'";
            else
                Sqlfullname = "";
            string SqlNamSinh = "";
            if (!txtTiepNhan_NamSinhTimKiem.Text.Equals(""))
                SqlNamSinh = " and Year(dateofbirth) = '" + Int32.Parse(txtTiepNhan_NamSinhTimKiem.Text) + "'";
            else
                SqlNamSinh = "";
            string SqlSex = "";
            if (!sex.Equals("") && !sex.Equals("3"))
                SqlSex = " and sex = " + Int32.Parse(sex);
            else
                SqlSex = "";
            string SqlCMND = "";
            if (txtTiepNhan_CMNDTimKiem.Text.Equals(""))
                SqlCMND = " and idcard like '%" + txtTiepNhan_CMNDTimKiem.Text + "%'";
            else
                SqlCMND = "";



            string queryNgayKham = "";
            if (!_ngaykhambenh_timkiem.Equals(""))
            {
                queryNgayKham = "and dateoftreatment = '" + _ngaykhambenh_timkiem + "'";
            }
            else
                queryNgayKham = "";
            query = "select TREATMENT.patientid,fullname,idcard,sex,dateofbirth,address,phonenumber,relative from PATIENT inner join TREATMENT on " +
                            " TREATMENT.patientid = PATIENT.patientid where 1=1" + SqlMaBenhNhan + Sqlfullname + SqlNamSinh + SqlCMND + SqlSex + queryNgayKham;


            try
            {
                string[] str = myQueryBL.doQuery(query);
                GridViewPatient.GridControl.DataSource = data.DataTablePatient(str);
                if (GridViewPatient.DataRowCount == 0)
                {
                    message.title = "Thông báo";
                    message.Content = "Không tìm thấy bệnh nhân nào.";
                    message.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void InitTabPatient()
        {
            dateEdit_NgayKham.EditValue = DateTime.Now;
        }
        private void btnAddPatient_DKKB_Click(object sender, EventArgs e)
        {
            if (txtFullName_DKKB.Text.Equals("") || txtCMND_DKKB.Text.Equals(""))
            {
                message.title = "Thông báo";
                message.Content = "Vui lòng nhập đầy đủ thông tin cần thiết.";
                message.ShowDialog();
                return;
            }

            Patient p = patientBL.createPatient();
            p.setFullName(txtFullName_DKKB.Text);
            p.setIdCard(txtCMND_DKKB.Text);
            p.setPhoneNumber(txtSoDienThoai_DKKB.Text);
            if (!_ngaysinh.Equals(""))
                p.setDateOfBirth(dt);

            p.setAddress(txtAddress_DKKB.Text);
            p.setRelative(txtNguoiThan_DKKB.Text);
            if (!Sex_DKKB.Equals(""))
            {
                if (Int32.Parse(Sex_DKKB.Trim()) == 1)
                    p.setSex(Person.Sex.MALE);
                else
                    if (Int32.Parse(Sex_DKKB.Trim()) == 2)
                        p.setSex(Person.Sex.FEMALE);
                    else
                        p.setSex(Person.Sex.NONE);
            }

            int IdPatient;
            if ((IdPatient = patientBL.addPatient(p)) > 0)
            {
                Treatment t = treatmentBL.createTreatment();
                t.setPatientId(IdPatient);
                DateTime d = DateTime.Now;
                dt = myQueryBL.getCMDateTime(d.Year, d.Month, d.Day);
                t.setDateOfTreatment(dt);
                if (!txtWeight.Text.Equals(""))
                    t.setWeight((float)Convert.ToDouble(txtWeight.Text));
                t.setTreatmentStatusId(1);
                t.setSymptom("");
                t.setDiagnosisId(0);
                t.setAdvice("");
                t.setDateOfReTreatment(dt);
                t.setDayOfUsingMedicine(0);
                t.setWorkerId(1);
                t.setTreatmentCost(0);
                t.setMedicineCost(0);
                t.setPayStatus(0);

                if (treatmentBL.addTreatment(t) > 0)
                {
                    message.title = "Thông báo";
                    message.Content = "Thêm thành công.";
                    message.ShowDialog();
                }
                else
                {
                    message.title = "Thông báo";
                    message.Content = "Thất bại khi thêm vào bảng khám bệnh.";
                    message.ShowDialog();
                }
            }
            else
            {
                message.title = "Thông báo lỗi";
                message.Content = "Xảy ra lỗi khi thêm. Vui lòng kiểm tra lại";
                message.ShowDialog();
                return;
            }
            dateEdit_NgayKham_EditValueChanged(sender, e);
            Refresh_DKKB();
        }

        private void btnUpdatePatient_DKKB_Click(object sender, EventArgs e)
        {
            if (txtFullName_DKKB.Text.Equals("") || txtCMND_DKKB.Text.Equals(""))
            {
                message.title = "Thông báo lỗi";
                message.Content = "Vui lòng nhập đầy đủ thông tin cần thiết.";
                message.ShowDialog();
                return;
            }
            Patient p = patientBL.createPatient();
            p.setPatientId(Int32.Parse(txtIDPatient_DKKB.Text));
            p.setFullName(txtFullName_DKKB.Text);
            p.setIdCard(txtCMND_DKKB.Text);
            p.setPhoneNumber(txtSoDienThoai_DKKB.Text);
            if (!_ngaysinh.Equals(""))
                p.setDateOfBirth(dt);
            p.setAddress(txtAddress_DKKB.Text);
            p.setRelative(txtNguoiThan_DKKB.Text);
            if (!Sex_DKKB.Equals(""))
            {
                if (Int32.Parse(Sex_DKKB.Trim()) == 1)
                    p.setSex(Person.Sex.MALE);
                else
                    if (Int32.Parse(Sex_DKKB.Trim()) == 2)
                        p.setSex(Person.Sex.FEMALE);
                    else
                        p.setSex(Person.Sex.NONE);
            }

            string query = "select patientid from PATIENT where fullname like N'%" + p.getFullName() + "%' and sex = " + (int)p.getSex() + " and dateofbirth = '"
                + _ngaysinh + "' and idcard like '" + p.getIdCard() + "' and phonenumber like '" + p.getPhoneNumber() + "' and  address like N'" + p.getAddress() +
                "' and relative = N'" + p.getRelative() + "'";

            string[] values = myQueryBL.doQuery(query);
            if (values.Length > 0)
            {
                return;
            }

            if (patientBL.updatePatient(p))
            {

                message.title = "Thông báo";
                message.Content = "Cập nhật thành công.";
                message.ShowDialog();
            }
            else
            {
                message.title = "Thông báo lỗi";
                message.Content = "Cập nhật thất bại.";
                message.ShowDialog();
                return;
            }
            // LoadAllPatient();
            dateEdit_NgayKham_EditValueChanged(sender, e);
            Refresh_DKKB();
        }

        public void Refresh_DKKB()
        {
            txtIDPatient_DKKB.Text = "";
            txtFullName_DKKB.Text = "";
            txtCMND_DKKB.Text = "";
            txtAddress_DKKB.Text = "";
            txtSoDienThoai_DKKB.Text = "";
            txtWeight.Text = "";
            txtNguoiThan_DKKB.Text = "";
            cbbxSexDkKhamBenh.Text = null;
            dateOfbirth_DKKB.Text = null;
            txtAge_DKKB.Text = "";
            Sex_DKKB = "";
            _ngaysinh = "";
            btnUpdatePatient_DKKB.Enabled = false;
            btnAddPatient_DKKB.Enabled = true;
        }
        string _ngaysinh = "";
        private void dateOfbirth_DKKB_EditValueChanged(object sender, EventArgs e)
        {
            DateTime d = dateOfbirth_DKKB.DateTime;
            DateTime now = DateTime.Now;
            _ngaysinh = d.Year + "/" + d.Month + "/" + d.Day;
            int age;
            txtAge_DKKB.Text = now.Year - d.Year + "";
            age = now.Year - d.Year;
            if (age <= 5)
                txtWeight.Enabled = true;
            else
                txtWeight.Enabled = false;

            dt = myQueryBL.getCMDateTime(d.Year, d.Month, d.Day);

        }

        private void dateofTreatment_EditValueChanged(object sender, EventArgs e)
        {
            //_ngaykhambenh_timkiem = dateofTreatment.DateTime.Year + "/" + dateofTreatment.DateTime.Month + "/" + dateofTreatment.DateTime.Day;
        }

        private void tablePatient_MouseClick(object sender, MouseEventArgs e)
        {
            if (GridViewPatient.GetFocusedDataSourceRowIndex() < 0)
                return;
            try
            {
                txtIDPatient_DKKB.Text = GridViewPatient.GetFocusedDataRow()["patientid"].ToString();
                txtFullName_DKKB.Text = GridViewPatient.GetFocusedDataRow()["fullname"].ToString();
                txtCMND_DKKB.Text = GridViewPatient.GetFocusedDataRow()["idcard"].ToString();
                txtAddress_DKKB.Text = GridViewPatient.GetFocusedDataRow()["address"].ToString();
                cbbxSexDkKhamBenh.Text = GridViewPatient.GetFocusedDataRow()["sex"].ToString();
                if (cbbxSexDkKhamBenh.Text.Equals("Nam"))
                    Sex_DKKB = "1";
                else
                    if (cbbxSexDkKhamBenh.Text.Equals("Nữ"))
                        Sex_DKKB = "2";
                    else
                        Sex_DKKB = "0";
                txtSoDienThoai_DKKB.Text = GridViewPatient.GetFocusedDataRow()["phonenumber"].ToString();
                txtNguoiThan_DKKB.Text = GridViewPatient.GetFocusedDataRow()["relative"].ToString();
                string[] values = GridViewPatient.GetFocusedDataRow()["dateofbirth"].ToString().Trim().Split('/');
                _ngaysinh = values[0] + "/" + values[1] + "/" + values[2];
                dateOfbirth_DKKB.EditValue = new DateTime(Int32.Parse(values[2]), Int32.Parse(values[1]), Int32.Parse(values[0]));
                btnUpdatePatient_DKKB.Enabled = true;
                btnAddPatient_DKKB.Enabled = false;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        string sex = "";
        private void cbbxSex_SelectedIndexChanged(object sender, EventArgs e)
        {
            sex = cbbxSex.SelectedIndex + "";
        }

        private string Sex_DKKB = "";
        private void cbbxSexDkKhamBenh_SelectedIndexChanged(object sender, EventArgs e)
        {

            Sex_DKKB = cbbxSexDkKhamBenh.SelectedIndex + "";
        }

        private void btnThemBenhNhan_Click(object sender, EventArgs e)
        {
            Refresh_DKKB();

        }

        string _ngaykham = "";
        private void dateEdit_NgayKham_EditValueChanged(object sender, EventArgs e)
        {
            DateTime d = dateEdit_NgayKham.DateTime.Date;
            _ngaykham = d.Year + "/" + d.Month + "/" + d.Day;
            CMDateTime dt = myQueryBL.getCMDateTime(d.Year, d.Month, d.Day);
            string query = "select TREATMENT.patientid,fullname,idcard,sex,dateofbirth,address,phonenumber,relative from PATIENT inner join TREATMENT on " +
                            " TREATMENT.patientid = PATIENT.patientid where dateoftreatment = '" + _ngaykham + "'";
            try
            {
                string[] str = myQueryBL.doQuery(query);
                GridViewPatient.GridControl.DataSource = data.DataTablePatient(str);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


        }


        private void txtTiepNhan_CMNDTimKiem_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtTiepNhan_MaSoTimKiem_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtTiepNhan_NamSinhTimKiem_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtAge_DKKB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCMND_DKKB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtSoDienThoai_DKKB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }


        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// //*****************************************************************Kết thúc tab tiếp nhận*********************************************************************//
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        //Sự kiện tắt một tabcontrol con
        private void tabControlMain_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabControl tabControl = (XtraTabControl)sender;
            ClosePageButtonEventArgs arg = (ClosePageButtonEventArgs)e;
            ((XtraTabPage)arg.Page).PageVisible = false;
        }

        //Init tab Hồ sơ bệnh án
        public void initTabHoSoBenhAn()
        {
            cbbHoSoBenhAn_TinhTrang.SelectedIndex = 0;
            tableViewHoSoBenhAn_DanhSachKhamBenh.GridControl.DataSource = Kb.getPatientListToday(myQueryBL, 1);
            DataTable dt = new DataTable();
            tableHoSoBenhAn_Thuoc.DataSource = dt;
            dt.Columns.Add("tenThuoc", typeof(string));
            dt.Columns.Add("sang", typeof(int));
            dt.Columns.Add("trua", typeof(int));
            dt.Columns.Add("chieu", typeof(int));
            dt.Columns.Add("toi", typeof(int));
            dt.Columns.Add("soLuong", typeof(int));
            dt.Columns.Add("cachDung", typeof(string));

            //Triệu chứng
            string sqlTrieuChung = "select symptomname from SYMPTOM";
            string[] strTrieuChung = myQueryBL.doQuery(sqlTrieuChung);
            dtTrieuChung = Kb.getTrieuChung(strTrieuChung);
            cbbHoSoBenhAn_TrieuChung.Properties.DataSource = dtTrieuChung;
            cbbHoSoBenhAn_TrieuChung.Properties.PopulateColumns();
            cbbHoSoBenhAn_TrieuChung.Properties.DisplayMember = "symptomname";

            //Chuẩn đoán
            string sqlChuanDoan = "select * from diagnosis";
            string[] strChuanDoan = myQueryBL.doQuery(sqlChuanDoan);
            dtChuanDoan = Kb.getChuanDoan(strChuanDoan);
            cbbHoSoBenhAn_ChuanDoan.Properties.DataSource = dtChuanDoan;
            cbbHoSoBenhAn_ChuanDoan.Properties.PopulateColumns();
            cbbHoSoBenhAn_ChuanDoan.Properties.DisplayMember = "diagnosisname";
            cbbHoSoBenhAn_ChuanDoan.Properties.ValueMember = "diagnosisid";
            cbbHoSoBenhAn_ChuanDoan.Properties.Columns["diagnosisid"].Visible = false;

            //Lời dặn
            string sqlLoiDan = "select advicename from ADVICE";
            string[] strLoiDan = myQueryBL.doQuery(sqlLoiDan);
            dtLoiDan = Kb.getLoiDan(strLoiDan);
            cbbHoSoBenhAn_LoiDan.Properties.DataSource = dtLoiDan;
            cbbHoSoBenhAn_LoiDan.Properties.PopulateColumns();
            cbbHoSoBenhAn_LoiDan.Properties.DisplayMember = "advicename";


            //Toa mẫu
            string sqlToaMau = "select * from PRESCRIPTIONFORM ";
            string[] strToaMau = myQueryBL.doQuery(sqlToaMau);
            cbbHoSoBenhAn_ToaThuocMau.Properties.DataSource = Kb.getToaThuocMau(strToaMau);
            cbbHoSoBenhAn_ToaThuocMau.Properties.PopulateColumns();
            cbbHoSoBenhAn_ToaThuocMau.Properties.DisplayMember = "prescriptionname";
            cbbHoSoBenhAn_ToaThuocMau.Properties.ValueMember = "prescriptionid";
            cbbHoSoBenhAn_ToaThuocMau.Properties.Columns["prescriptionid"].Visible = false;

            //Thuốc
            string sqlThuoc = "select medicineid, medicinename, medicinestrength, medicineunitname  from medicine inner join medicineunit on medicine.medicineunitid = medicineunit.medicineunitid";
            string[] strThuoc = myQueryBL.doQuery(sqlThuoc);
            tableViewHoSoBenhAn_TenThuoc.DataSource = Kb.getThuoc(strThuoc);
            tableViewHoSoBenhAn_TenThuoc.PopulateColumns();
            tableViewHoSoBenhAn_TenThuoc.DisplayMember = "medicinename";
            tableViewHoSoBenhAn_TenThuoc.ValueMember = "medicineid";
            tableViewHoSoBenhAn_TenThuoc.Columns["medicineid"].Visible = false;

            //Cách dùng
            string sqlCachDung = "select * from usage";
            string[] strCachDung = myQueryBL.doQuery(sqlCachDung);
            dtCachDung = Kb.getCachDung(strCachDung);
            tableViewHoSoBenhAn_CachDung.DataSource = dtCachDung;
            tableViewHoSoBenhAn_CachDung.PopulateColumns();
            tableViewHoSoBenhAn_CachDung.DisplayMember = "usagename";
            tableViewHoSoBenhAn_CachDung.ValueMember = "usageid";
            tableViewHoSoBenhAn_CachDung.Columns["usageid"].Visible = false;
            //Max mã cách dùng
            string sqlMaxCachDung = "select max(usageid) from usage";
            string[] strMaxCachDung = myQueryBL.doQuery(sqlMaxCachDung);
            maxCachDung = Kb.getMaxId(strMaxCachDung) + 1;
            tableViewHoSoBenhAn_CachDung.ProcessNewValue += (object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e) =>
            {
                DataRow Row;
                RepositoryItemLookUpEdit Edit;

                Edit = ((LookUpEdit)sender).Properties;

                if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                    return;

                Row = dtCachDung.NewRow();
                Row["usageid"] = maxCachDung;
                Row["usagename"] = e.DisplayValue;

                dtCachDung.Rows.Add(Row);
                maxCachDung++;
                e.Handled = true;
            };

            //số lượng thuốc
            tableViewHoSoBenhAn_Sang.Leave += (object sender, EventArgs e) =>
            {
                HoSoBenhAnSoLuongThuoc();
            };
            tableViewHoSoBenhAn_Trua.Leave += (object sender, EventArgs e) =>
            {
                HoSoBenhAnSoLuongThuoc();
            };
            tableViewHoSoBenhAn_Chieu.Leave += (object sender, EventArgs e) =>
            {
                HoSoBenhAnSoLuongThuoc();
            };
            tableViewHoSoBenhAn_Toi.Leave += (object sender, EventArgs e) =>
            {
                HoSoBenhAnSoLuongThuoc();
            };

        }

        //set Số lượng thuốc
        public void HoSoBenhAnSoLuongThuoc()
        {
            int sang = 0;
            int trua = 0;
            int chieu = 0;
            int toi = 0;
            int ngayThuoc = 1;
            try
            {
                ngayThuoc = Convert.ToInt32(txtHoSoBenhAn_NgayThuoc.Text);
            }
            catch (Exception) { }

            try
            {
                sang = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetRowCellValue(tableViewHoSoBenhAn_Thuoc.FocusedRowHandle, tableViewHoSoBenhAn_Thuoc.Columns[1]));
            }
            catch (Exception) { }
            try
            {
                trua = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetRowCellValue(tableViewHoSoBenhAn_Thuoc.FocusedRowHandle, tableViewHoSoBenhAn_Thuoc.Columns[2]));
            }
            catch (Exception) { }
            try
            {
                chieu = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetRowCellValue(tableViewHoSoBenhAn_Thuoc.FocusedRowHandle, tableViewHoSoBenhAn_Thuoc.Columns[3]));
            }
            catch (Exception) { }
            try
            {
                toi = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetRowCellValue(tableViewHoSoBenhAn_Thuoc.FocusedRowHandle, tableViewHoSoBenhAn_Thuoc.Columns[4]));
            }
            catch (Exception) { }
            tableViewHoSoBenhAn_Thuoc.SetRowCellValue(tableViewHoSoBenhAn_Thuoc.FocusedRowHandle, tableViewHoSoBenhAn_Thuoc.Columns[5], (sang + trua + chieu + toi) * ngayThuoc);
        }
        //Init tab Toa Mẫu
        public void initTabToaMau()
        {
            //Triệu chứng
            string sqlToaMau = "select * from prescriptionform";
            string[] strToaMau = myQueryBL.doQuery(sqlToaMau);
            try
            {
                tableViewToaThuocMau_DanhSach.GridControl.DataSource = Tm.DanhSachToaMau(strToaMau);
            }
            catch (Exception) { }


            DataTable dt = new DataTable();
            tableToaThuocMau_Thuoc.DataSource = dt;
            dt.Columns.Add("tenThuoc", typeof(string));
            dt.Columns.Add("sang", typeof(int));
            dt.Columns.Add("trua", typeof(int));
            dt.Columns.Add("chieu", typeof(int));
            dt.Columns.Add("toi", typeof(int));
            dt.Columns.Add("soLuong", typeof(int));
            dt.Columns.Add("cachDung", typeof(string));

            //Thuốc
            string sqlThuoc = "select medicineid, medicinename, medicinestrength, medicineunitname  from medicine inner join medicineunit on medicine.medicineunitid = medicineunit.medicineunitid";
            string[] strThuoc = myQueryBL.doQuery(sqlThuoc);
            tableViewToaMau_TenThuoc.DataSource = Kb.getThuoc(strThuoc);
            tableViewToaMau_TenThuoc.PopulateColumns();
            tableViewToaMau_TenThuoc.DisplayMember = "medicinename";
            tableViewToaMau_TenThuoc.ValueMember = "medicineid";

            tableViewToaMau_TenThuoc.EditValueChanged += (object sender, EventArgs e) =>
            {
                int rowFocus = tableViewToaThuocMau_Thuoc.FocusedRowHandle;

            };

            //Cách dùng
            string sqlCachDung = "select * from usage";
            string[] strCachDung = myQueryBL.doQuery(sqlCachDung);
            dtCachDung = Kb.getCachDung(strCachDung);
            tableViewToaMau_CachDung.DataSource = dtCachDung;
            tableViewToaMau_CachDung.PopulateColumns();
            tableViewToaMau_CachDung.DisplayMember = "usagename";
            tableViewToaMau_CachDung.ValueMember = "usageid";
            tableViewToaMau_CachDung.Columns["usageid"].Visible = false;

            //Max mã cách dùng
            string sqlMaxCachDung = "select max(usageid) from usage";
            string[] strMaxCachDung = myQueryBL.doQuery(sqlMaxCachDung);
            maxCachDung = Kb.getMaxId(strMaxCachDung) + 1;
            tableViewToaMau_CachDung.ProcessNewValue += (object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e) =>
            {
                DataRow Row;
                RepositoryItemLookUpEdit Edit;

                Edit = ((LookUpEdit)sender).Properties;

                if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                    return;

                Row = dtCachDung.NewRow();
                Row["usageid"] = maxCachDung;
                Row["usagename"] = e.DisplayValue;

                dtCachDung.Rows.Add(Row);
                maxCachDung++;

                e.Handled = true;
            };
            //Tính số lượng thuốc

            tableViewToaMau_Sang.Leave += (object sender, EventArgs e) =>
            {
                ToaMauSoLuong();
            };
            tableViewToaMau_Trua.Leave += (object sender, EventArgs e) =>
            {
                ToaMauSoLuong();
            };
            tableViewToaMau_Chieu.Leave += (object sender, EventArgs e) =>
            {
                ToaMauSoLuong();
            };
            tableViewToaMau_Toi.Leave += (object sender, EventArgs e) =>
            {
                ToaMauSoLuong();
            };
        }
        public void ToaMauSoLuong()
        {
            int sang = 0;
            int trua = 0;
            int chieu = 0;
            int toi = 0;
            try
            {
                sang = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetRowCellValue(tableViewToaThuocMau_Thuoc.FocusedRowHandle, tableViewToaThuocMau_Thuoc.Columns[1]));
            }
            catch (Exception) { }
            try
            {
                trua = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetRowCellValue(tableViewToaThuocMau_Thuoc.FocusedRowHandle, tableViewToaThuocMau_Thuoc.Columns[2]));
            }
            catch (Exception) { }
            try
            {
                chieu = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetRowCellValue(tableViewToaThuocMau_Thuoc.FocusedRowHandle, tableViewToaThuocMau_Thuoc.Columns[3]));
            }
            catch (Exception) { }
            try
            {
                toi = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetRowCellValue(tableViewToaThuocMau_Thuoc.FocusedRowHandle, tableViewToaThuocMau_Thuoc.Columns[4]));
            }
            catch (Exception) { }
            tableViewToaThuocMau_Thuoc.SetRowCellValue(tableViewToaThuocMau_Thuoc.FocusedRowHandle, tableViewToaThuocMau_Thuoc.Columns[5], sang + trua + chieu + toi);
        }
        //init thanh toan
        public void initThanhToan()
        {
            int index = cbbThanhToan_KieuThanhToan.SelectedIndex;
            DateTime time = DateTime.Now;

            if (index == 0)
            {
                tableViewThanhToan_DanhSach.GridControl.DataSource = Kb.getPatientListPayment(myQueryBL, 0, "", "", 0, "", "today", 1);
            }
            else if (index == 1)
            {
                tableViewThanhToan_DanhSach.GridControl.DataSource = Kb.getPatientListPayment(myQueryBL, 0, "", "", 0, "", "today", 2);
            }
        }


        //Sự kiện chọn một tab nào đó
        private void tabControlMain_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            if (tabControlMain.SelectedTabPage == tabDangNhap)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }
                //Do something


                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }

            }
            else if (tabControlMain.SelectedTabPage == tabTiepNhan)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                InitTabPatient();

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabHoSoBenhAn)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                initTabHoSoBenhAn();

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabKhaiBaoThuoc)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }
                InitTabMedicine();

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }

            }
            else if (tabControlMain.SelectedTabPage == tabDanhmuc)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                cbbDanhMuc_ThongTin.SelectedIndex = 0;

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabNhanVienBacSy)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                InitTabWorker();

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }

            }
            else if (tabControlMain.SelectedTabPage == tabToaMau)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }
                initTabToaMau();


                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabDoanhThu)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }
                
                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }

            }
            else if (tabControlMain.SelectedTabPage == tabSuDungThuoc)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabPhanQuyen)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabCauHinh)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabNhapKho)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
            else if (tabControlMain.SelectedTabPage == tabThanhToan)
            {
                //Loading start
                try
                {
                    splashScreenManager.ShowWaitForm();
                }
                catch (Exception) { }
                initThanhToan();

                //Loading stop
                try
                {
                    splashScreenManager.CloseWaitForm();
                }
                catch (Exception) { }
            }
        }

        /**
         ** BarItemClick
         **/
        //Click tabItem Tiếp nhận
        private void barBtnTiepNhan_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }
            if (tabTiepNhan.PageVisible == false)
            {
                tabTiepNhan.PageVisible = true;
                tabControlMain.SelectedTabPage = tabTiepNhan;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabTiepNhan;
            }
            InitTabPatient();

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }

        }
        //Click tabItem Bệnh án

        private void barBtnBenhAn_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabHoSoBenhAn.PageVisible == false)
            {
                tabHoSoBenhAn.PageVisible = true;
                tabControlMain.SelectedTabPage = tabHoSoBenhAn;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabHoSoBenhAn;
            }
            initTabHoSoBenhAn();

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }
        //Sự kiện tạo mới một trường combobox triệu chứng
        private void cbbHoSoBenhAn_TrieuChung_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            DataRow Row;
            RepositoryItemLookUpEdit Edit;

            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;

            Row = dtTrieuChung.NewRow();
            Row["symptomname"] = e.DisplayValue;

            dtTrieuChung.Rows.Add(Row);

            e.Handled = true;
        }



        private void barButtonItemPhanQuyenSuDung_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabPhanQuyen.PageVisible == false)
            {
                tabPhanQuyen.PageVisible = true;
                tabControlMain.SelectedTabPage = tabPhanQuyen;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabPhanQuyen;
            }


            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemThuoc_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabKhaiBaoThuoc.PageVisible == false)
            {
                tabKhaiBaoThuoc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabKhaiBaoThuoc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabKhaiBaoThuoc;
            }
            InitTabMedicine();

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemCachDung_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabDanhmuc.PageVisible == false)
            {
                tabDanhmuc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }

            cbbDanhMuc_ThongTin.Text = "Cách Dùng";
            cbbDanhMuc_ThongTin.SelectedIndex = 0;

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemDuongDung_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabDanhmuc.PageVisible == false)
            {
                tabDanhmuc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            cbbDanhMuc_ThongTin.Text = "Đường Dùng";
            cbbDanhMuc_ThongTin.SelectedIndex = 1;

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemLoiDan_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabDanhmuc.PageVisible == false)
            {
                tabDanhmuc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            cbbDanhMuc_ThongTin.Text = "Lời Dặn";
            cbbDanhMuc_ThongTin.SelectedIndex = 2;

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemChuanDoan_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabDanhmuc.PageVisible == false)
            {
                tabDanhmuc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            cbbDanhMuc_ThongTin.Text = "Chẩn Đoán Bệnh";
            cbbDanhMuc_ThongTin.SelectedIndex = 3;

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemTrieuChung_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabDanhmuc.PageVisible == false)
            {
                tabDanhmuc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabDanhmuc;
            }
            cbbDanhMuc_ThongTin.Text = "Triệu Chứng";
            cbbDanhMuc_ThongTin.SelectedIndex = 4;

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemNhanVienBacSy_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabNhanVienBacSy.PageVisible == false)
            {
                tabNhanVienBacSy.PageVisible = true;
                tabControlMain.SelectedTabPage = tabNhanVienBacSy;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabNhanVienBacSy;
            }
            InitTabWorker();

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }
        //Khai báo toa mẫu
        private void barButtonItemToaThuocMau_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }


            if (tabToaMau.PageVisible == false)
            {
                tabToaMau.PageVisible = true;
                tabControlMain.SelectedTabPage = tabToaMau;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabToaMau;
            }
            initTabToaMau();


            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemDoanhThu_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabDoanhThu.PageVisible == false)
            {
                tabDoanhThu.PageVisible = true;
                tabControlMain.SelectedTabPage = tabDoanhThu;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabDoanhThu;
            }


            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barButtonItemSuDungThuoc_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabSuDungThuoc.PageVisible == false)
            {
                tabSuDungThuoc.PageVisible = true;
                tabControlMain.SelectedTabPage = tabSuDungThuoc;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabSuDungThuoc;
            }

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barBtnThanhToan_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabThanhToan.PageVisible == false)
            {
                tabThanhToan.PageVisible = true;
                tabControlMain.SelectedTabPage = tabThanhToan;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabThanhToan;
            }
            initThanhToan();
            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barBtnNhapKho_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabNhapKho.PageVisible == false)
            {
                tabNhapKho.PageVisible = true;
                tabControlMain.SelectedTabPage = tabNhapKho;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabNhapKho;
            }

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        private void barBtnCauHinh_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            if (tabCauHinh.PageVisible == false)
            {
                tabCauHinh.PageVisible = true;
                tabControlMain.SelectedTabPage = tabCauHinh;
            }
            else
            {
                tabControlMain.SelectedTabPage = tabCauHinh;
            }

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }
        private void tabTiepNhan_Click(object sender, EventArgs e)
        {
            //Loading start
            try
            {
                splashScreenManager.ShowWaitForm();
            }
            catch (Exception) { }

            InitTabPatient();

            //Loading stop
            try
            {
                splashScreenManager.CloseWaitForm();
            }
            catch (Exception) { }
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //*************************************************************Bắt đầu  tab worker*********************************************************************************//
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public void InitTabWorker()
        {
            Position[] p = positionBl.getAllPosition();
            cbbxPosition_Worker.Properties.DataSource = data.ConvertArrPositionToDatatable(p);
            cbbxPosition_Worker.Properties.DisplayMember = "positonname";
            cbbxPosition_Worker.Properties.ValueMember = "positionid";
            cbbxPosition_Worker.Properties.PopulateColumns();
            cbbxPosition_Worker.Properties.Columns["positionid"].Visible = false;

            cbbxPosition_SearchWorker.Properties.DataSource = data.ConvertArrPositionToDatatable(p);
            cbbxPosition_SearchWorker.Properties.DisplayMember = "positonname";
            cbbxPosition_SearchWorker.Properties.ValueMember = "positionid";
            cbbxPosition_SearchWorker.Properties.PopulateColumns();
            cbbxPosition_SearchWorker.Properties.Columns["positionid"].Visible = false;
            loadDataTableWorker();

        }



        private void gridControl_SearchWorker_MouseClick(object sender, MouseEventArgs e)
        {
            if (gridViewSearchWorker.GetFocusedDataSourceRowIndex() < 0)
                return;
            try
            {

                txtID_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["workerid"].ToString();
                txtFullName_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["fullname"].ToString();
                txtCMND_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["idcard"].ToString();
                txtAddress_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["address"].ToString();
                cbbxSex_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["sex"].ToString();
                txtPhoneNuber_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["phonenumber"].ToString();
                cbbxPosition_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["positionname"].ToString();
                string[] values = gridViewSearchWorker.GetFocusedDataRow()["dateofbirth"].ToString().Trim().Split('/');
                DateOfBirth_Worker.EditValue = new DateTime(Int32.Parse(values[2]), Int32.Parse(values[1]), Int32.Parse(values[0]));
                txtUser_Worker.Text = gridViewSearchWorker.GetFocusedDataRow()["username"].ToString();
                if (cbbxStatus_SearchWorker.SelectedIndex == 0)
                    cbbxStatus_Worker.Text = "Đã Nghỉ Việc";
                else
                    cbbxStatus_Worker.Text = "Đang Làm";
                _positionwoker = cbbxPosition_Worker.EditValue.ToString();
                _dateofbirthWorker = DateOfBirth_Worker.DateTime.ToShortDateString();
                txtPassWord_Worker.Text = "######";
                btnAddWorker.Enabled = false;
                btnUpdateWorker.Enabled = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public void loadDataTableWorker()
        {
            string query = "select workerid,fullname,dateofbirth,idcard,sex,address,phonenumber,positonname,username,password from WORKER inner join POSITION on " +
                " POSITION.positionid = WORKER.positionid where status = 1";
            string[] str = myQueryBL.doQuery(query);
            if (str.Length > 0)
            {
                DataGridWorker.DataSource = data.DataTableWorker(str);
            }
        }



        private void DataGridWorker_MouseClick(object sender, MouseEventArgs e)
        {
            if (gridViewWoker.GetFocusedDataSourceRowIndex() < 0)
                return;
            try
            {

                txtID_Worker.Text = gridViewWoker.GetFocusedDataRow()["workerid"].ToString();
                txtFullName_Worker.Text = gridViewWoker.GetFocusedDataRow()["fullname"].ToString();
                txtCMND_Worker.Text = gridViewWoker.GetFocusedDataRow()["idcard"].ToString();
                txtAddress_Worker.Text = gridViewWoker.GetFocusedDataRow()["address"].ToString();
                cbbxSex_Worker.Text = gridViewWoker.GetFocusedDataRow()["sex"].ToString();
                txtPhoneNuber_Worker.Text = gridViewWoker.GetFocusedDataRow()["phonenumber"].ToString();
                cbbxPosition_Worker.Text = gridViewWoker.GetFocusedDataRow()["positionname"].ToString();
                string[] values = gridViewWoker.GetFocusedDataRow()["dateofbirth"].ToString().Trim().Split('/');
                DateOfBirth_Worker.EditValue = new DateTime(Int32.Parse(values[2]), Int32.Parse(values[1]), Int32.Parse(values[0]));
                txtUser_Worker.Text = gridViewWoker.GetFocusedDataRow()["username"].ToString();
                cbbxStatus_Worker.Text = "Đang Làm";
                _positionwoker = cbbxPosition_Worker.EditValue.ToString();
                _dateofbirthWorker = DateOfBirth_Worker.DateTime.ToShortDateString();
                txtPassWord_Worker.Text = "######";
                btnAddWorker.Enabled = false;
                btnUpdateWorker.Enabled = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        string _sexWorker = "";
        private void cbbxSex_Worker_SelectedIndexChanged(object sender, EventArgs e)
        {
            _sexWorker = cbbxSex_Worker.SelectedIndex + "";
        }
        string _dateofbirthWorker = "";
        private void DateOfBirth_Worker_EditValueChanged(object sender, EventArgs e)
        {
            DateTime d = DateOfBirth_Worker.DateTime;
            dt = myQueryBL.getCMDateTime(d.Year, d.Month, d.Day);
            _dateofbirthWorker = DateOfBirth_Worker.DateTime.ToShortDateString();
        }

        string _positionwoker = "";
        private void cbbxPosition_Worker_EditValueChanged(object sender, EventArgs e)
        {
            _positionwoker = cbbxPosition_Worker.EditValue.ToString();
        }

        public void RefreshTabWorker()
        {

            txtID_Worker.Text = "###";
            txtFullName_Worker.Text = "";
            txtCMND_Worker.Text = "";
            txtUser_Worker.Text = "";
            txtPassWord_Worker.Text = "";
            txtPhoneNuber_Worker.Text = "";
            txtAddress_Worker.Text = "";
            cbbxSex_Worker.Text = null;
            cbbxPosition_Worker.EditValue = 0;
            cbbxStatus_Worker.Text = null;
            DateOfBirth_Worker.Text = "";
            btnAddWorker.Enabled = true;
            btnUpdateWorker.Enabled = false;

        }

        private void btnAddWorker_Click(object sender, EventArgs e)
        {
            if (txtFullName_Worker.Text.Equals("") || txtCMND_Worker.Text.Equals("") || txtUser_Worker.Text.Equals("") || txtPassWord_Worker.Text.Equals("")
                || _positionwoker.Equals("") || _sexWorker.Equals("") || _dateofbirthWorker.Equals(""))
            {
                message.title = "Error";
                message.Content = "Vui lòng nhập đầy đủ thông tin";
                message.ShowDialog();
                return;
            }

            Worker w = workerBl.createWorker();
            w.setFullName(txtFullName_Worker.Text);
            w.setIdCard(txtCMND_Worker.Text);
            w.setUsername(txtUser_Worker.Text);
            w.setPassword(txtPassWord_Worker.Text);
            w.setPhoneNumber(txtPhoneNuber_Worker.Text);
            w.setAddress(txtAddress_Worker.Text);
            w.setPositionId(Int32.Parse(_positionwoker));
            w.setStatus(1);

            if (_sexWorker == "1")
                w.setSex(Person.Sex.MALE);
            else
                if (_sexWorker == "2")
                    w.setSex(Person.Sex.FEMALE);
                else
                    w.setSex(Person.Sex.NONE);

            string query = "select workerid from WORKER where idcard = '" + w.getIdCard() + "'";
            string[] values = myQueryBL.doQuery(query);
            if (values.Length > 0)
            {
                message.title = "Error";
                message.Content = "Nhân viên đã được đăng ký";
                message.ShowDialog();
                return;
            }

            if (workerBl.addWorker(w) > 0)
            {
                message.title = "Thông báo";
                message.Content = "Đăng ký thành công";
                message.ShowDialog();
                RefreshTabWorker();
                loadDataTableWorker();
            }
            else
            {
                message.title = "Lỗi";
                message.Content = "Đăng ký thất bại";
                message.ShowDialog();
            }

        }

        private void btnUpdateWorker_Click(object sender, EventArgs e)
        {
            if (txtFullName_Worker.Text.Equals("") || txtCMND_Worker.Text.Equals("") || txtUser_Worker.Text.Equals("") || txtPassWord_Worker.Text.Equals("")
               || _positionwoker.Equals("") || _sexWorker.Equals("") || _dateofbirthWorker.Equals("") || cbbxStatus_Worker.Text.Equals(""))
            {
                message.title = "Lỗi";
                message.Content = "Vui lòng nhập đầy đủ thông tin";
                message.ShowDialog();
                return;
            }
            Worker w = workerBl.createWorker();
            w.setWorkerId(Int32.Parse(txtID_Worker.Text));
            w.setFullName(txtFullName_Worker.Text);
            w.setIdCard(txtCMND_Worker.Text);
            w.setUsername(txtUser_Worker.Text);
            w.setPassword(txtPassWord_Worker.Text);
            w.setPhoneNumber(txtPhoneNuber_Worker.Text);
            w.setAddress(txtAddress_Worker.Text);
            w.setPositionId(Int32.Parse(_positionwoker));
            w.setStatus((short)cbbxStatus_Worker.SelectedIndex);
            w.setDateOfBirth(dt);

            if (_sexWorker == "1")
                w.setSex(Person.Sex.MALE);
            else
                if (_sexWorker == "2")
                    w.setSex(Person.Sex.FEMALE);
                else
                    w.setSex(Person.Sex.NONE);
            string _ngaysinhWorker = w.getDateOfBirth().getYear() + "/" + w.getDateOfBirth().getMonth() + "/" + w.getDateOfBirth().getDay();
            string query = "select workerid from WORKER where fullname like N'" + w.getFullName() + "' and idcard = '" + w.getIdCard() +
                "' and sex =" + (int)w.getSex() + " and dateofbirth = '" + _ngaysinhWorker + "'  and address like N'" + w.getAddress() +
                "' and phonenumber like '" + w.getPhoneNumber() + "' and status = " + w.getStatus();
            string[] values = myQueryBL.doQuery(query);

            if (values.Length > 0 && txtPassWord_Worker.Text.Equals("######"))
            {
                return;
            }

            if (workerBl.updateWorker(w))
            {
                message.title = "Thông báo";
                message.Content = "Cập nhật thành công";
                message.ShowDialog();
                RefreshTabWorker();
                loadDataTableWorker();
            }
            else
            {
                message.title = "Lỗi";
                message.Content = "Cập nhật thất bại";
                message.ShowDialog();
            }
        }

        private void btnSearch_Worker_Click(object sender, EventArgs e)
        {
            string queryIdWorker = "";
            if (!txtWorkerID_Search.Text.Equals(""))
            {
                queryIdWorker = " and workerid = " + Int32.Parse(txtWorkerID_Search.Text);
            }
            else
                queryIdWorker = "";
            string queryFullName = "";
            if (!txtFullName_SearchWorker.Text.Equals(""))
            {
                queryFullName = " and fullname = '%" + txtFullName_SearchWorker.Text + "%'";
            }
            else
                queryFullName = "";
            string queryDateOfBirth = "";

            if (!txtDayofBirth_SearchWorker.Text.Equals(""))
            {
                queryDateOfBirth = " and Year(dateofbirth) = " + Int32.Parse(txtDayofBirth_SearchWorker.Text);
            }
            else
                queryDateOfBirth = "";
            string queryPositionWorker = "";
            if (!cbbxPosition_SearchWorker.Text.Equals(""))
            {
                queryPositionWorker = " and WORKER.positionid = " + Int32.Parse(_searchPositionWoker);
            }
            else
                queryPositionWorker = "";

            string queryStatsus = "";
            if (!cbbxStatus_SearchWorker.Text.Equals(""))
            {
                queryStatsus = " and status = " + Int32.Parse(_statusworker);
            }
            else
                queryStatsus = "";

            string query = "select workerid,fullname,dateofbirth,idcard,sex,address,phonenumber,positonname,username,password from WORKER inner join POSITION on " +
                " POSITION.positionid = WORKER.positionid where 1 = 1" + queryIdWorker + queryFullName + queryPositionWorker + queryStatsus;
            string[] str = myQueryBL.doQuery(query);
            gridViewSearchWorker.GridControl.DataSource = data.DataTableWorker(str);



        }

        private void btnNewWorker_Click(object sender, EventArgs e)
        {
            RefreshTabWorker();
        }
        string _searchPositionWoker = "";
        private void cbbxPosition_SearchWorker_EditValueChanged(object sender, EventArgs e)
        {
            _searchPositionWoker = cbbxPosition_SearchWorker.EditValue.ToString();
        }

        string _statusworker = "";
        private void cbbxStatus_SearchWorker_SelectedIndexChanged(object sender, EventArgs e)
        {
            _statusworker = cbbxStatus_SearchWorker.SelectedIndex + "";
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //*************************************************************Kết thúc tab worker*********************************************************************************//
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        // sự kiện change combobox tình trạng
        // tab Hồ sơ bệnh án
        private void cbbHoSoBenhAn_TinhTrang_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbHoSoBenhAn_TinhTrang.Text != null)
            {
                int index = cbbHoSoBenhAn_TinhTrang.SelectedIndex;
                if (index == 0)
                {
                    tableViewHoSoBenhAn_DanhSachKhamBenh.GridControl.DataSource = Kb.getPatientListToday(myQueryBL, 1);
                }
                else if (index == 1)
                {
                    tableViewHoSoBenhAn_DanhSachKhamBenh.GridControl.DataSource = Kb.getPatientListToday(myQueryBL, 2);
                }
                else if (index == 2)
                {
                    tableViewHoSoBenhAn_DanhSachKhamBenh.GridControl.DataSource = Kb.getPatientListToday(myQueryBL, 3);
                }
            }
        }
        //Sự kiện click button search trong tab hồ sơ bệnh án
        private void btnHoSoBenhAn_TimKiem_Click(object sender, EventArgs e)
        {
            //Format datetime
            dateHoSoBenhAn_TkNgayKham.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            dateHoSoBenhAn_TkNgayKham.Properties.DisplayFormat.FormatString = "dd/MM/yyyy";

            string hoTen = txtHoSoBenhAn_TkHoTen.Text;
            string namSinh = txtHoSoBenhAn_TkNamSinh.Text;
            int gioiTinh = cbbHoSoBenhAn_TkGioiTinh.SelectedIndex;
            string soCMND = txtHoSoBenhAn_TkCMND.Text;
            string ngayKham = dateHoSoBenhAn_TkNgayKham.Text;

            if (hoTen == "" && namSinh == "" && gioiTinh == 0 && soCMND == "" && ngayKham == "")
            {
                message.Content = "Chưa nhập nội dung tìm kiếm";
                message.title = "Thông báo tìm kiếm";
                message.ShowDialog();
            }
            else
            {
                splashScreenManager.ShowWaitForm();
                tableViewHoSoBenhAn_DanhSachKhamBenh.GridControl.DataSource = Kb.getPatientListBySearch(myQueryBL, hoTen, namSinh, gioiTinh, soCMND, ngayKham);
                splashScreenManager.CloseWaitForm();
                cbbHoSoBenhAn_TinhTrang.Text = "";
            }

        }

        //Sự kiện get dữ liệu bệnh nhân từ table khám bệnh
        private void tableHoSoBenhAn_DanhSachBenhNhan_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                txtHoSoBenhAn_MaSo.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["treatmentid"].ToString();
                txtHoSoBenhAn_HoTen.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["fullname"].ToString();
                cbbHoSoBenhAn_GioiTinh.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["sex"].ToString();
                txtHoSoBenhAn_NgaySinh.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["dateofbirth"].ToString();
                txtHoSoBenhAn_DiaChi.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["address"].ToString();
                txtHoSoBenhAn_DienThoai.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["phonenumber"].ToString();
                txtHoSoBenhAn_NguoiThan.Text = tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["relative"].ToString();

                //get lịch sử khám bệnh
                int patientid = Convert.ToInt32(tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["patientid"].ToString());
                string sqlTreatmentHistory = "select treatmentid, dateoftreatment, diagnosisname from ((treatment inner join patient on treatment.patientid = patient.patientid) inner join diagnosis on diagnosis.diagnosisid = treatment.diagnosisid) where patient.patientid=" + patientid + " order by dateoftreatment asc";
                string[] strTreatmentHistory = myQueryBL.doQuery(sqlTreatmentHistory);
                tableHoSoBenhAn_LichSuKhamBenh.DataSource = Kb.getTreatmentHistory(strTreatmentHistory);

                //set lưu enable
                if (txtHoSoBenhAn_MaSo.Text != "")
                {
                    btnHoSoBenhAn_Luu.Enabled = true;
                    btnHoSoBenhAn_InToa.Enabled = true;
                }
            }
            catch (Exception)
            {

            }
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //*****************************************************************Bắt đầu Tab danh mục************************************************************************//
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        int _indexdanhmuc = 0;
        private void cbbDanhMuc_ThongTin_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbDanhMuc_ThongTin.SelectedIndex == 0)
            {
                _indexdanhmuc = 0;
                loadDataUsage();
                //load data cách dùng
                //Cách dùng

            }
            else
                if (cbbDanhMuc_ThongTin.SelectedIndex == 1)
                {
                    //load data đường dùng
                    _indexdanhmuc = 1;
                    loadDatarouteofadmin();

                }
                else
                    if (cbbDanhMuc_ThongTin.SelectedIndex == 2)
                    {
                        //load data lời dặn
                        _indexdanhmuc = 2;
                        loadDataAdvice();
                    }
                    else
                        if (cbbDanhMuc_ThongTin.SelectedIndex == 3)
                        {
                            //load data chẩn đoán
                            _indexdanhmuc = 3;
                            loadDataDiagnosis();

                        }
                        else
                        {
                            //load data triệu chứng
                            _indexdanhmuc = 4;
                            loadDataSysmptom();
                        }


        }

        public void loadDataUsage()
        {
            ColumnsID.Caption = "Mã Số";
            ColumnsName.Caption = "Tên Cách Dùng";
            ColumnsID.FieldName = "usageid";
            ColumnsName.FieldName = "usagename";
            string sqlCachDung = "select * from usage";
            string[] strCachDung = myQueryBL.doQuery(sqlCachDung);
            gridViewCategories.GridControl.DataSource = Kb.getCachDung(strCachDung);
        }

        public void loadDatarouteofadmin()
        {
            RefreshComponentOfcategories();
            ColumnsID.Caption = "Mã Số";
            ColumnsName.Caption = "Tên Đường Dùng";
            ColumnsID.FieldName = "routeofadminid";
            ColumnsName.FieldName = "routeofadminname";
            string query = "select * from ROUTEOFADMINISTRATION";
            string[] str = myQueryBL.doQuery(query);
            gridViewCategories.GridControl.DataSource = data.DataTablerouteofadministration(str);
        }

        public void loadDataAdvice()
        {
            RefreshComponentOfcategories();
            ColumnsID.Caption = "Mã Số";
            ColumnsName.Caption = "Lời Dặn";
            ColumnsID.FieldName = "adviceid";
            ColumnsName.FieldName = "advicename";
            string query = "select * from ADVICE";
            string[] str = myQueryBL.doQuery(query);
            gridViewCategories.GridControl.DataSource = data.DataTableAdvice(str);


        }
        public void loadDataDiagnosis()
        {
            RefreshComponentOfcategories();
            ColumnsID.Caption = "Mã Số";
            ColumnsName.Caption = "Tên Loại Bệnh";
            ColumnsID.FieldName = "diagnosisid";
            ColumnsName.FieldName = "diagnosisname";
            string query = "select * from DIAGNOSIS";
            string[] str = myQueryBL.doQuery(query);
            gridViewCategories.GridControl.DataSource = data.DataTableDIAGNOSIS(str);
        }

        public void loadDataSysmptom()
        {
            RefreshComponentOfcategories();
            ColumnsID.Caption = "Mã Số";
            ColumnsName.Caption = "Triệu Chứng";
            ColumnsID.FieldName = "symptomid";
            ColumnsName.FieldName = "symptomname";
            string query = "select * from SYMPTOM";
            string[] str = myQueryBL.doQuery(query);
            gridViewCategories.GridControl.DataSource = data.DataTableSymptom(str);
        }

        private void btnDanhMuc_TaoMoi_Click(object sender, EventArgs e)
        {
            RefreshComponentOfcategories();
        }

        public void RefreshComponentOfcategories()
        {
            btnDanhMuc_Luu.Enabled = true;
            txtDanhMuc_MaSo.Text = "";
            txtDanhMuc_Ten.Text = "";
            btnDanhMuc_Sua.Enabled = false;
        }
        private void btnDanhMuc_Luu_Click(object sender, EventArgs e)
        {
            //string str = "";
            if (_indexdanhmuc == 0)
            {
                //Thêm cách dùng
                if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                {
                    message.title = "Lỗi";
                    message.Content = "Vui lòng nhập đầy đủ thông tin";
                    message.ShowDialog();
                    return;
                }
                string query = "insert into usage(usagename) values(N'" + txtDanhMuc_Ten.Text + "')";
                if (myQueryBL.doNonQuery(query))
                {
                    message.title = "Thông báo";
                    message.Content = "Thêm thành công";
                    message.ShowDialog();
                    RefreshComponentOfcategories();
                    loadDataUsage();
                    return;
                }
                else
                {
                    message.title = "Lỗi";
                    message.Content = "Thất bại";
                    message.ShowDialog();
                }
            }
            else
                if (_indexdanhmuc == 1)
                {
                    //Thêm đường dùng
                    if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                    {
                        message.title = "Lỗi";
                        message.Content = "Vui lòng nhập đầy đủ thông tin";
                        message.ShowDialog();
                        RefreshComponentOfcategories();
                        loadDatarouteofadmin();
                        return;
                    }
                    RouteOfAdmin roa = medicineBL.createRouteOfAdmin();
                    roa.setMedRouteOfAdminName(txtDanhMuc_Ten.Text);
                    if (medicineBL.addRouteOfAdmin(roa))
                    {
                        message.title = "Thông báo";
                        message.Content = "Thêm thành công";
                        message.ShowDialog();
                        loadDatarouteofadmin();
                        RefreshComponentOfcategories();
                        return;
                    }
                    else
                    {
                        MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                    if (_indexdanhmuc == 2)
                    {
                        if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                        {
                            message.title = "Lỗi";
                            message.Content = "Vui lòng nhập đầy đủ thông tin";
                            message.ShowDialog();
                            return;
                        }
                        if (treatmentBL.addAdvice(txtDanhMuc_Ten.Text))
                        {
                            message.title = "Thông báo";
                            message.Content = "Thêm thành công";
                            message.ShowDialog();
                            loadDataAdvice();
                            RefreshComponentOfcategories();
                            return;
                        }
                        else
                        {
                            MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                        if (_indexdanhmuc == 3)
                        {
                            if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                            {
                                message.title = "Lỗi";
                                message.Content = "Vui lòng nhập đầy đủ thông tin";
                                message.ShowDialog();
                                return;
                            }
                            if (treatmentBL.addDiagnosis(txtDanhMuc_Ten.Text))
                            {
                                message.title = "Thông báo";
                                message.Content = "Thêm thành công";
                                message.ShowDialog();
                                loadDataDiagnosis();
                                RefreshComponentOfcategories();
                                return;
                            }
                            else
                            {
                                MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        else
                        {
                            if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                            {
                                message.title = "Lỗi";
                                message.Content = "Vui lòng nhập đầy đủ thông tin";
                                message.ShowDialog();
                                return;
                            }
                            if (treatmentBL.addSymptom(txtDanhMuc_Ten.Text))
                            {
                                message.title = "Thông báo";
                                message.Content = "Thêm thành công";
                                message.ShowDialog();
                                loadDataSysmptom();
                                RefreshComponentOfcategories();
                                return;
                            }
                            else
                            {
                                MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
        }

        private void btnDanhMuc_Sua_Click(object sender, EventArgs e)
        {
            string query = "";
            string[] values;
            if (_indexdanhmuc == 0)
            {
                //cập nhật cách dùng
                if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                {
                    message.title = "Lỗi";
                    message.Content = "Vui lòng nhập đầy đủ thông tin";
                    message.ShowDialog();
                    RefreshComponentOfcategories();
                    loadDataUsage();
                    return;
                }
                query = "select usageid from usage where  usagename = N'" + txtDanhMuc_Ten.Text + "'";
                values = myQueryBL.doQuery(query);
                if (values.Length > 0)
                {
                    return;
                }
                query = "update usage set usagename =N'" + txtDanhMuc_Ten.Text + "' where usageid = " + Int32.Parse(txtDanhMuc_MaSo.Text);
                if (myQueryBL.doNonQuery(query))
                {
                    message.title = "Thông báo";
                    message.Content = "Cập nhật  thành công";
                    message.ShowDialog();
                    loadDataUsage();
                    RefreshComponentOfcategories();
                }
                else
                {
                    message.title = "Lỗi";
                    message.Content = "Cập nhật thất bại";
                    message.ShowDialog();
                }
            }
            else
                if (_indexdanhmuc == 1)
                {
                    //Cập nhật đường dùng
                    if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                    {
                        message.title = "Lỗi";
                        message.Content = "Vui lòng nhập đầy đủ thông tin";
                        message.ShowDialog();

                        return;
                    }
                    query = "select routeofadminid from ROUTEOFADMINISTRATION where  routeofadminname = N'" + txtDanhMuc_Ten.Text + "'";
                    values = myQueryBL.doQuery(query);
                    if (values.Length > 0)
                    {
                        return;
                    }
                    query = "update ROUTEOFADMINISTRATION set routeofadminname = N'" + txtDanhMuc_Ten.Text + "' where routeofadminid = " + Int32.Parse(txtDanhMuc_MaSo.Text);
                    if (myQueryBL.doNonQuery(query))
                    {
                        message.title = "Thông báo";
                        message.Content = "Cập nhật  thành công";
                        message.ShowDialog();
                        RefreshComponentOfcategories();
                        loadDatarouteofadmin();
                        return;
                    }
                }
                else
                    if (_indexdanhmuc == 2)
                    {
                        if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                        {
                            message.title = "Lỗi";
                            message.Content = "Vui lòng nhập đầy đủ thông tin";
                            message.ShowDialog();

                            return;
                        }
                        query = "select adviceid from advice where  advicename = N'" + txtDanhMuc_Ten.Text + "'";
                        values = myQueryBL.doQuery(query);
                        if (values.Length > 0)
                        {
                            return;
                        }
                        if (treatmentBL.updateAdvice(Int32.Parse(txtDanhMuc_MaSo.Text), txtDanhMuc_Ten.Text))
                        {
                            message.title = "Thông báo";
                            message.Content = "Cập nhật thành công";
                            message.ShowDialog();
                            RefreshComponentOfcategories();
                            loadDataAdvice();
                            return;
                        }
                        else
                        {
                            MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                        if (_indexdanhmuc == 3)
                        {
                            if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                            {
                                message.title = "Lỗi";
                                message.Content = "Vui lòng nhập đầy đủ thông tin";
                                message.ShowDialog();
                                return;
                            }
                            query = "select diagnosisid from diagnosis where  diagnosisname = N'" + txtDanhMuc_Ten.Text + "'";
                            values = myQueryBL.doQuery(query);
                            if (values.Length > 0)
                            {
                                return;
                            }
                            if (treatmentBL.updateDiagnosis(Int32.Parse(txtDanhMuc_MaSo.Text), txtDanhMuc_Ten.Text))
                            {
                                message.title = "Thông báo";
                                message.Content = "Cập nhật thành công";
                                message.ShowDialog();
                                loadDataDiagnosis();
                                RefreshComponentOfcategories();
                                return;
                            }
                            else
                            {
                                MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        else
                        {
                            if (txtDanhMuc_Ten.Text.Trim().Equals(""))
                            {
                                message.title = "Lỗi";
                                message.Content = "Vui lòng nhập đầy đủ thông tin";
                                message.ShowDialog();
                                return;
                            }
                            query = "select symptomid from Symptom where  Symptomname = N'" + txtDanhMuc_Ten.Text + "'";
                            values = myQueryBL.doQuery(query);
                            if (values.Length > 0)
                            {
                                return;
                            }

                            if (treatmentBL.updateSymptom(Int32.Parse(txtDanhMuc_MaSo.Text), txtDanhMuc_Ten.Text))
                            {
                                message.title = "Thông báo";
                                message.Content = "Cập nhật thành công";
                                message.ShowDialog();
                                loadDataSysmptom();
                                RefreshComponentOfcategories();
                                return;
                            }
                            else
                            {
                                MessageBox.Show("Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                        }
        }

        private void tableDanhMuc_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (gridViewCategories != null)
                {
                    if (_indexdanhmuc == 0)
                    {
                        txtDanhMuc_MaSo.Text = gridViewCategories.GetFocusedDataRow()["usageid"].ToString();
                        txtDanhMuc_Ten.Text = gridViewCategories.GetFocusedDataRow()["usagename"].ToString();
                    }
                    else

                        if (_indexdanhmuc == 1)
                        {
                            txtDanhMuc_MaSo.Text = gridViewCategories.GetFocusedDataRow()["routeofadminid"].ToString();
                            txtDanhMuc_Ten.Text = gridViewCategories.GetFocusedDataRow()["routeofadminname"].ToString();
                        }
                        else
                            if (_indexdanhmuc == 2)
                            {
                                txtDanhMuc_MaSo.Text = gridViewCategories.GetFocusedDataRow()["adviceid"].ToString();
                                txtDanhMuc_Ten.Text = gridViewCategories.GetFocusedDataRow()["advicename"].ToString();
                            }
                            else
                                if (_indexdanhmuc == 3)
                                {
                                    txtDanhMuc_MaSo.Text = gridViewCategories.GetFocusedDataRow()["diagnosisid"].ToString();
                                    txtDanhMuc_Ten.Text = gridViewCategories.GetFocusedDataRow()["diagnosisname"].ToString();
                                }
                                else
                                {
                                    txtDanhMuc_MaSo.Text = gridViewCategories.GetFocusedDataRow()["symptomid"].ToString();
                                    txtDanhMuc_Ten.Text = gridViewCategories.GetFocusedDataRow()["symptomname"].ToString();
                                }
                    btnDanhMuc_Luu.Enabled = false;
                    btnDanhMuc_Sua.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }



        //*****************************************************************Kêt Thúc tab danh mục************************************************************************//

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //*****************************************************************Băt đầu Tab khai báo thuốc vật tư****************************************************************//
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        DataTable dtThuocVatTu = new DataTable();
        int maxThuoc = 0;
        public void InitTabMedicine()
        {

            MedUnit[] m = medicineBL.getAllMedUnit();
            if (m != null)
            {
                cbbThuoc_DonVi.Properties.DataSource = data.ConvertArrMedUnitToDatatable(m);
                cbbThuoc_DonVi.Properties.DisplayMember = "medicineunitname";
                cbbThuoc_DonVi.Properties.ValueMember = "medicineunitid";
                cbbThuoc_DonVi.Properties.PopulateColumns();
                cbbThuoc_DonVi.Properties.Columns["medicineunitid"].Visible = false;

                cbbThuoc_TkDonVi.Properties.DataSource = data.ConvertArrMedUnitToDatatable(m);
                cbbThuoc_TkDonVi.Properties.DisplayMember = "medicineunitname";
                cbbThuoc_TkDonVi.Properties.ValueMember = "medicineunitid";
                cbbThuoc_TkDonVi.Properties.PopulateColumns();
                cbbThuoc_TkDonVi.Properties.Columns["medicineunitid"].Visible = false;
            }


            string queryTableMedicineGroup = "select medicinegroupid,medicinegroupname from MEDICINEGROUP";
            string[] str = myQueryBL.doQuery(queryTableMedicineGroup);
            if (str != null)
            {
                cbbThuoc_NhomThuoc.Properties.DataSource = data.DataTableMedicineGroup(str);
                cbbThuoc_NhomThuoc.Properties.DisplayMember = "medicinegroupname";
                cbbThuoc_NhomThuoc.Properties.ValueMember = "medicinegroupid";
                cbbThuoc_NhomThuoc.Properties.PopulateColumns();
                cbbThuoc_NhomThuoc.Properties.Columns["medicinegroupid"].Visible = false;

                cbbThuoc_TkNhomThuoc.Properties.DataSource = data.DataTableMedicineGroup(str);
                cbbThuoc_TkNhomThuoc.Properties.DisplayMember = "medicinegroupname";
                cbbThuoc_TkNhomThuoc.Properties.ValueMember = "medicinegroupid";
                cbbThuoc_TkNhomThuoc.Properties.PopulateColumns();
                cbbThuoc_TkNhomThuoc.Properties.Columns["medicinegroupid"].Visible = false;
            }

            string queryTableRouteofadminitration = "select * from ROUTEOFADMINISTRATION";
            string[] s = myQueryBL.doQuery(queryTableRouteofadminitration);

            if (s != null)
            {
                cbbThuoc_DuongDung.Properties.DataSource = data.DataTablerouteofadministration(s);
                cbbThuoc_DuongDung.Properties.DisplayMember = "routeofadminname";
                cbbThuoc_DuongDung.Properties.ValueMember = "routeofadminid";
                cbbThuoc_DuongDung.Properties.PopulateColumns();
                cbbThuoc_DuongDung.Properties.Columns["routeofadminid"].Visible = false;
            }

            if (s.Length > 0)
            {
                cbbThuoc_DuongDung.Properties.DataSource = data.DataTablerouteofadministration(s);
                cbbThuoc_DuongDung.Properties.DisplayMember = "routeofadminname";
                cbbThuoc_DuongDung.Properties.ValueMember = "routeofadminid";
                cbbThuoc_DuongDung.Properties.PopulateColumns();
                cbbThuoc_DuongDung.Properties.Columns["routeofadminid"].Visible = false;

            }

            string queryTableMedicine = "select medicineid,medicinename from MEDICINE";
            string[] tablemedicine = myQueryBL.doQuery(queryTableMedicine);
            if (tablemedicine.Length > 0)
            {
                dtThuocVatTu = data.DataTableMedicine(tablemedicine);
                cbbThuoc_TenThuoc.Properties.DataSource = dtThuocVatTu;
                cbbThuoc_TenThuoc.Properties.DisplayMember = "medicinename";
                cbbThuoc_TenThuoc.Properties.ValueMember = "medicineid";
                cbbThuoc_TenThuoc.Properties.PopulateColumns();
                cbbThuoc_TenThuoc.Properties.Columns["medicineid"].Visible = false;


            }

            loadDataTableMedicine();
        }
        private void cbbThuoc_TenThuoc_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            string sqlMaxThuoc = "select max(medicineid) from medicine";
            string[] strMaxThuoc = myQueryBL.doQuery(sqlMaxThuoc);
            maxThuoc = Kb.getMaxId(strMaxThuoc) + 1;

            DataRow Row;
            RepositoryItemLookUpEdit Edit;

            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;

            Row = dtThuocVatTu.NewRow();
            Row["medicineid"] = maxThuoc;
            Row["medicinename"] = e.DisplayValue;

            dtThuocVatTu.Rows.Add(Row);
            maxThuoc++;
            e.Handled = true;
        }
        private void tableThuoc_DanhSachTimKiem_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (gridViewMedicine != null)
                {
                    txtThuoc_MaSo.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["medicineid"].ToString();
                    cbbThuoc_TenThuoc.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["medicinename"].ToString();
                    txtThuoc_HamLuong.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["medicinestrength"].ToString();
                    txtThuoc_SoLuong.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["quantitytotal"].ToString();
                    cbbThuoc_NhomThuoc.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["medicinegroupname"].ToString();
                    cbbThuoc_DonVi.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["medicineunitname"].ToString();
                    cbbThuoc_DuongDung.Text = gridViewTk_ThuocVatTu.GetFocusedDataRow()["routeofadminname"].ToString();
                    btnThuoc_CapNhat.Enabled = true;
                    btnThuoc_Luu.Enabled = false;

                    _groupMedicineId = cbbThuoc_NhomThuoc.EditValue.ToString();
                    _idMedicineUnit = cbbThuoc_DonVi.EditValue.ToString();
                    _duongdung = cbbThuoc_DuongDung.EditValue.ToString();
                    _medicineid = cbbThuoc_TenThuoc.EditValue.ToString();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        private void cbbThuoc_TenThuoc_Leave(object sender, EventArgs e)
        {
            string tenThuoc = cbbThuoc_TenThuoc.Text;
            int id = Int32.Parse(cbbThuoc_TenThuoc.EditValue.ToString());
            string query = "select medicineid from MEDICINE where medicinename like '" + tenThuoc + "'";
            string[] values = myQueryBL.doQuery(query);
            if (values.Length > 0)
            {
                query = "select medicinestrength,quantitytotal,routeofadministrationid,medicineunitid,medicinegroupid from MEDICINE where medicineid = " + id;
                values = myQueryBL.doQuery(query);
                string[] row = values[0].Split(new string[] { "<<_>>" }, StringSplitOptions.None);
                txtThuoc_HamLuong.Text = row[0];
                txtThuoc_SoLuong.Text = row[1];
                cbbThuoc_DuongDung.EditValue = Int32.Parse(row[2]);
                cbbThuoc_DonVi.EditValue = Int32.Parse(row[3]);
                cbbThuoc_NhomThuoc.EditValue = Int32.Parse(row[4]);
                txtThuoc_MaSo.Text = id + "";
                if (btnThuoc_Luu.Enabled == true)
                    btnThuoc_Luu.Enabled = false;
                if (btnThuoc_CapNhat.Enabled == false)
                    btnThuoc_CapNhat.Enabled = true;
            }
            _medicineid = tenThuoc;

        }


        string _idUnit = "";
        private void cbbThuoc_TkDonVi_EditValueChanged(object sender, EventArgs e)
        {
            _idUnit = cbbThuoc_TkDonVi.EditValue.ToString();
        }

        string _idGroupMedicine = "";
        private void cbbThuoc_TkNhomThuoc_EditValueChanged(object sender, EventArgs e)
        {
            _idGroupMedicine = cbbThuoc_TkNhomThuoc.EditValue.ToString();

        }

        private void btnTk_ThuocVatTu_Click(object sender, EventArgs e)
        {
            string queryIdMedicine = "";
            if (!txtThuoc_TkMaSo.Text.Equals(""))
            {
                queryIdMedicine = " and medicineid = " + Int32.Parse(txtThuoc_TkMaSo.Text);
            }
            else
                queryIdMedicine = "";
            string queryMedicineName = "";

            if (!txtThuoc_TkTenThuoc.Text.Equals(""))
            {
                queryMedicineName = " and medicinename like N'%" + txtThuoc_TkTenThuoc.Text + "%' ";
                // MessageBox.Show(queryMedicineName);
            }
            else
                queryMedicineName = "";
            string queryMedicinestrength = "";

            if (!txtThuoc_TkHamLuong.Text.Equals(""))
            {
                queryMedicinestrength = " and medicinestrength like N'%" + txtThuoc_TkHamLuong.Text + "%'";
            }
            else
                queryMedicinestrength = "";

            string queryIdUnitMedicine = "";
            if (!_idUnit.Equals(""))
            {
                queryIdUnitMedicine = " and  MEDICINE.medicineunitid = " + Int32.Parse(_idUnit);
            }
            else
                queryIdUnitMedicine = "";

            string querymedicinegroup = "";
            if (!_idGroupMedicine.Equals(""))
            {
                querymedicinegroup = " and MEDICINEGROUP.medicinegroupid = " + Int32.Parse(_idGroupMedicine);
            }
            else
                querymedicinegroup = "";

            string query = "select medicineid,medicinename,medicinestrength,ROUTEOFADMINISTRATION.routeofadminname,MEDICINEUNIT.medicineunitname,MEDICINEGROUP.medicinegroupname,quantitytotal " +
                "  from MEDICINE inner join ROUTEOFADMINISTRATION on MEDICINE.routeofadministrationid = ROUTEOFADMINISTRATION.routeofadminid inner join MEDICINEUNIT " +
                " on MEDICINEUNIT.medicineunitid = MEDICINE.medicineunitid inner join MEDICINEGROUP on MEDICINEGROUP.medicinegroupid = MEDICINE.medicinegroupid where 1 = 1 " +
                queryIdMedicine + queryMedicineName + queryMedicinestrength + queryIdUnitMedicine + querymedicinegroup;
            string[] str = myQueryBL.doQuery(query);

            gridViewTk_ThuocVatTu.GridControl.DataSource = data.ConvertArrMedicineToDatatable(str);




        }

        private void cbbThuoc_TenThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            RefreshComponentOfTabMedicine();
        }

        private void btnNewMedicine_Click(object sender, EventArgs e)
        {
            RefreshComponentOfTabMedicine();
            btnThuoc_CapNhat.Enabled = false;
            btnThuoc_Luu.Enabled = true;
        }



        private void tableThuoc_Thuoc_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (gridViewMedicine != null)
                {
                    txtThuoc_MaSo.Text = gridViewMedicine.GetFocusedDataRow()["medicineid"].ToString();
                    cbbThuoc_TenThuoc.Text = gridViewMedicine.GetFocusedDataRow()["medicinename"].ToString();
                    txtThuoc_HamLuong.Text = gridViewMedicine.GetFocusedDataRow()["medicinestrength"].ToString();
                    txtThuoc_SoLuong.Text = gridViewMedicine.GetFocusedDataRow()["quantitytotal"].ToString();
                    cbbThuoc_NhomThuoc.Text = gridViewMedicine.GetFocusedDataRow()["medicinegroupname"].ToString();
                    cbbThuoc_DonVi.Text = gridViewMedicine.GetFocusedDataRow()["medicineunitname"].ToString();
                    cbbThuoc_DuongDung.Text = gridViewMedicine.GetFocusedDataRow()["routeofadminname"].ToString();
                    btnThuoc_CapNhat.Enabled = true;
                    btnThuoc_Luu.Enabled = false;

                    _groupMedicineId = cbbThuoc_NhomThuoc.EditValue.ToString();
                    _idMedicineUnit = cbbThuoc_DonVi.EditValue.ToString();
                    _duongdung = cbbThuoc_DuongDung.EditValue.ToString();
                    _medicineid = cbbThuoc_TenThuoc.EditValue.ToString();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void RefreshComponentOfTabMedicine()
        {
            txtThuoc_MaSo.Text = "###";
            cbbThuoc_TenThuoc.EditValue = 0;
            txtThuoc_SoLuong.Text = "0";
            txtThuoc_HamLuong.Text = "";
            cbbThuoc_NhomThuoc.EditValue = 0;
            cbbThuoc_DonVi.EditValue = 0;
            cbbThuoc_DuongDung.EditValue = 0;
            _groupMedicineId = "";
            _idMedicineUnit = "";
            _duongdung = "";
            _medicineid = "";
        }



        private void btnThuoc_Luu_Click(object sender, EventArgs e)
        {
            if (_medicineid.Equals("") || _groupMedicineId.Equals("") || _idMedicineUnit.Equals("") || _duongdung.Equals(""))
            {
                message.Content = "Vui lòng nhập đầy đủ thông tin.";
                message.title = "Lỗi";
                message.ShowDialog();
                return;
            }
            Medicine m = medicineBL.createMedicine();
            m.setMedicineName(cbbThuoc_TenThuoc.Text);
            m.setStrength(txtThuoc_HamLuong.Text);
            m.setRouteOfAdministrationId(Int32.Parse(_duongdung));
            m.setMedUnitId(Int32.Parse(_idMedicineUnit));
            m.setMedGroupId(Int32.Parse(_groupMedicineId.Trim()));
            if (txtThuoc_SoLuong.Text.Equals(""))
                m.setQuantityTotal(Int32.Parse(txtThuoc_SoLuong.Text));
            m.setStatus(1);

            if (medicineBL.addMedicine(m) > 0)
            {
                message.Content = "Thêm thành công";
                message.title = "Thông báo";
                message.ShowDialog();
                loadDataTableMedicine();
                RefreshComponentOfTabMedicine();
            }
            else
            {
                message.Content = "Failed";
                message.title = "Error";
                message.ShowDialog();
                return;
            }
        }

        private void btnThuoc_CapNhat_Click(object sender, EventArgs e)
        {
            if (_medicineid.Equals("") || _groupMedicineId.Equals("") || _idMedicineUnit.Equals("") || _duongdung.Equals(""))
            {
                message.Content = "Vui lòng nhập đầy đủ thông tin.";
                message.title = "Lỗi";
                message.ShowDialog();
                return;
            }
            Medicine m = medicineBL.createMedicine();
            m.setMedId(Int32.Parse(txtThuoc_MaSo.Text));
            m.setMedicineName(cbbThuoc_TenThuoc.Text);
            m.setStrength(txtThuoc_HamLuong.Text);
            m.setRouteOfAdministrationId(Int32.Parse(_duongdung));
            m.setMedUnitId(Int32.Parse(_idMedicineUnit));
            m.setMedGroupId(Int32.Parse(_groupMedicineId));
            m.setStatus(0);
            if (!txtThuoc_SoLuong.Text.Equals(""))
                m.setQuantityTotal(Int32.Parse(txtThuoc_SoLuong.Text));

            string query = "select medicineid from MEDICINE where medicinename like N'" + m.getMedicineName() + "' and medicinestrength = N'" + m.getStrength() +
               "' and routeofadministrationid = " + m.getRouteOfAdministrationId() + " and medicineunitid = " + m.getMedUnitId() + " and medicinegroupid = " + m.getMedGroupId() +
                " and quantitytotal = " + m.getQuantityTotal();


            query = "update MEDICINE set status = 0 where medicineid =" + m.getMedId();
            if (myQueryBL.doNonQuery(query))
            {
                query = "insert into MEDICINE(medicinename,medicinestrength,routeofadministrationid,medicineunitid,medicinegroupid,quantitytotal,status) values('" + m.getMedicineName()
                    + "','" + m.getStrength() + "'," + m.getRouteOfAdministrationId() + "," + m.getMedUnitId() + "," + m.getMedGroupId() + "," + m.getQuantityTotal() + ",1)";
                if (myQueryBL.doNonQuery(query))
                {
                    message.Content = "Cập nhật thành công";
                    message.title = "Thông báo";
                    message.ShowDialog();
                    loadDataTableMedicine();
                }
                else
                {
                    message.Content = "Cập nhật thất bại";
                    message.title = "Thông báo";
                    message.ShowDialog();
                }
            }
            else
            {
                message.Content = "Cập nhật thất bại";
                message.title = "Thông báo";
                message.ShowDialog();
            }

            

        }
        string _medicineid = "";
        private void cbbThuoc_TenThuoc_EditValueChanged(object sender, EventArgs e)
        {
            _medicineid = cbbThuoc_TenThuoc.EditValue.ToString();
        }



        string _duongdung = "";
        private void cbbThuoc_DuongDung_EditValueChanged(object sender, EventArgs e)
        {
            _duongdung = cbbThuoc_DuongDung.EditValue.ToString();
        }

        string _groupMedicineId = "";
        private void cbbThuoc_NhomThuoc_EditValueChanged(object sender, EventArgs e)
        {
            _groupMedicineId = cbbThuoc_NhomThuoc.EditValue.ToString();

        }
        string _idMedicineUnit = "";
        private void cbbThuoc_DonVi_EditValueChanged(object sender, EventArgs e)
        {
            _idMedicineUnit = cbbThuoc_DonVi.EditValue.ToString();
        }




        public void loadDataTableMedicine()
        {
            string query = "select medicineid,medicinename,medicinestrength,ROUTEOFADMINISTRATION.routeofadminname,MEDICINEUNIT.medicineunitname,MEDICINEGROUP.medicinegroupname,quantitytotal " +
                "  from MEDICINE inner join ROUTEOFADMINISTRATION on MEDICINE.routeofadministrationid = ROUTEOFADMINISTRATION.routeofadminid inner join MEDICINEUNIT " +
                " on MEDICINEUNIT.medicineunitid = MEDICINE.medicineunitid inner join MEDICINEGROUP on MEDICINEGROUP.medicinegroupid = MEDICINE.medicinegroupid where MEDICINE.status = 1";
            string[] str = myQueryBL.doQuery(query);
            if (str.Length > 0)
            {
                gridViewMedicine.GridControl.DataSource = data.ConvertArrMedicineToDatatable(str);
            }

        }

        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// //*************************************************************Kết thúc tab khai báo thuốc vật tư************************************************************//
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        //Sự kiện bệnh nhân mới - Hồ sơ bệnh án
        private void btnHoSoBenhAn_BenhNhanMoi_Click(object sender, EventArgs e)
        {
            txtHoSoBenhAn_MaSo.Text = "";
            txtHoSoBenhAn_HoTen.Text = "";
            txtHoSoBenhAn_NgaySinh.Text = "";
            cbbHoSoBenhAn_GioiTinh.Text = "";
            txtHoSoBenhAn_DiaChi.Text = "";
            txtHoSoBenhAn_DienThoai.Text = "";
            txtHoSoBenhAn_NguoiThan.Text = "";
            cbbHoSoBenhAn_TrieuChung.Text = "";
            cbbHoSoBenhAn_ChuanDoan.Text = "";
            cbbHoSoBenhAn_LoiDan.Text = "";
            dateHoSoBenhAn_NgayHen.Text = "";
            txtHoSoBenhAn_NgayThuoc.Text = "7";
            cbbHoSoBenhAn_ToaThuocMau.EditValue = 1;
            DataTable table = new DataTable();
            tableHoSoBenhAn_Thuoc.DataSource = table;
        }
        private void btnHoSoBenhAn_InToa_Click(object sender, EventArgs e)
        {
            //variable

            ReportDonThuoc report = new ReportDonThuoc();
            //parameter
            report.Parameters.GetByName("Report_HoTen").Value = txtHoSoBenhAn_HoTen.Text;
            report.Parameters.GetByName("Report_Tuoi").Value = " " + txtHoSoBenhAn_NgaySinh.Text + " Phái: " + cbbHoSoBenhAn_GioiTinh.Text;
            report.Parameters.GetByName("Report_DiaChi").Value = txtHoSoBenhAn_DiaChi.Text;
            report.Parameters.GetByName("Report_ChuanDoan").Value = cbbHoSoBenhAn_ChuanDoan.Text;
            report.Parameters.GetByName("Report_NgayKham").Value = DateTime.Now;
            report.Parameters.GetByName("Report_MaKhamBenh").Value = txtHoSoBenhAn_MaSo.Text;

            for (int i = 0; i < tableViewHoSoBenhAn_Thuoc.DataRowCount; i++)
            {
                string tenThuoc = "";
                string hamLuong = "";
                string soLuong = "0";
                string cachDung = "";
                int k = i + 1;
                string name = "Report_Thuoc" + k;
                tenThuoc = tableViewHoSoBenhAn_Thuoc.GetRowCellDisplayText(i, "tenThuoc").ToString();
                //hamLuong = tableViewHoSoBenhAn_Thuoc.GetRowCellValue(i, "medicineunitname").ToString();
                soLuong = tableViewHoSoBenhAn_Thuoc.GetRowCellValue(i, "soLuong").ToString();
                cachDung = tableViewHoSoBenhAn_Thuoc.GetRowCellDisplayText(i, "cachDung").ToString();
                report.Parameters.GetByName(name).Value = tenThuoc;
                report.Parameters.GetByName("Report_SoLuong" + k).Value = soLuong;
                report.Parameters.GetByName("Report_CachDung" + k).Value = cachDung;

                //object row = tableViewHoSoBenhAn_TenThuoc.GetDataSourceRowByKeyValue(tableViewHoSoBenhAn_TenThuoc.ValueMember);
                //if (row != null)
                //{
                //    string columnValue = ((DataRowView)row)["medicineunitname"].ToString();
                //    MessageBox.Show(columnValue);
                //}
            }


            ReportPrintTool tool = new ReportPrintTool(report);
            tool.ShowPreview();
        }


        private void grCtrlDangNhap_Paint(object sender, PaintEventArgs e)
        {

        }

        private void grCtrlTitle_Paint(object sender, PaintEventArgs e)
        {

        }




        //click close application
        private void iExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void cbbHoSoBenhAn_ChuanDoan_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            DataRow Row;
            RepositoryItemLookUpEdit Edit;

            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;

            Row = dtChuanDoan.NewRow();
            Row["diagnosisname"] = e.DisplayValue;

            dtChuanDoan.Rows.Add(Row);

            e.Handled = true;
        }

        private void cbbHoSoBenhAn_LoiDan_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            DataRow Row;
            RepositoryItemLookUpEdit Edit;

            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;

            Row = dtLoiDan.NewRow();
            Row["advicename"] = e.DisplayValue;

            dtLoiDan.Rows.Add(Row);

            e.Handled = true;
        }


        //Xóa row trong tab hồ sơ bệnh án thuốc
        private void tableHoSoBenhAn_Thuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.Control)
            {
                if (MessageBox.Show("Delete row?", "Confirmation", MessageBoxButtons.YesNo) !=
                  DialogResult.Yes)
                    return;
                tableViewHoSoBenhAn_Thuoc.DeleteRow(tableViewHoSoBenhAn_Thuoc.FocusedRowHandle);
            }
        }

        //sự kiện chép toa mẫu
        private void btnHoSoBenhAn_ChepToa_Click(object sender, EventArgs e)
        {
            int index = 0;
            int ngayThuoc = 0;
            try
            {
                index = Convert.ToInt32(cbbHoSoBenhAn_ToaThuocMau.EditValue.ToString());
            }
            catch (Exception) { }
            tableViewHoSoBenhAn_Thuoc.GridControl.DataSource = Kb.getPrescriptionFormById(myQueryBL, index);
            try
            {
                ngayThuoc = Convert.ToInt32(txtHoSoBenhAn_NgayThuoc.Text);
            }
            catch (Exception) { }
            if (tableViewHoSoBenhAn_Thuoc.DataRowCount == 0)
            {
                message.title = "Chép toa mẫu";
                message.Content = "Toa mẫu không có dữ liệu nào.";
                message.ShowDialog();
            }
            else
            {
                for (int i = 0; i < tableViewHoSoBenhAn_Thuoc.DataRowCount; i++)
                {
                    int maThuoc = 0;
                    int soLuong = 0;

                    try
                    {
                        maThuoc = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetRowCellValue(i, "maThuoc"));
                        soLuong = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetRowCellValue(i, "soLuong"));


                    }
                    catch (Exception) { }
                    tableViewHoSoBenhAn_Thuoc.SetRowCellValue(i, tableViewHoSoBenhAn_Thuoc.Columns[0], maThuoc);
                    tableViewHoSoBenhAn_Thuoc.SetRowCellValue(i, "soLuong", soLuong * ngayThuoc);
                }
                message.title = "Chép toa mẫu";
                message.Content = "Hoàn tất công việc chép toa mẫu.";
                message.ShowDialog();
            }


        }
        //Sự kiện toa mẫu mới
        private void btnToaMau_ToaMauMoi_Click(object sender, EventArgs e)
        {
            txtToaMau_MaSo.Text = "";
            txtToaMau_TenToa.Text = "";
            txtToaMau_MoTa.Text = "";
            DataTable dt = new DataTable();
            tableToaThuocMau_Thuoc.DataSource = dt;
            dt.Columns.Add("tenThuoc", typeof(string));
            dt.Columns.Add("sang", typeof(int));
            dt.Columns.Add("trua", typeof(int));
            dt.Columns.Add("chieu", typeof(int));
            dt.Columns.Add("toi", typeof(int));
            dt.Columns.Add("soLuong", typeof(int));
            dt.Columns.Add("cachDung", typeof(string));
            btnToaMau_CapNhat.Enabled = false;
            btnToaMau_XoaToaMau.Enabled = false;
            btnToaMau_LuuToaMau.Enabled = true;

        }
        //Lưu toa thuốc mẫu
        private void btnToaMau_LuuToaMau_Click(object sender, EventArgs e)
        {
            string tenToaMau = txtToaMau_TenToa.Text;
            string moTa = txtToaMau_MoTa.Text;
            if (tenToaMau == "")
            {
                message.title = "Toa Mẫu";
                message.Content = "Chưa nhập tên toa mẫu";
                message.ShowDialog();
            }
            else
            {
                Prescription prescription = prescriptionBL.createPrescrition();
                prescription.setPrescriptionName(tenToaMau);
                prescription.setPrescriptionNote(moTa);

                int row = tableViewToaThuocMau_Thuoc.DataRowCount;
                if (row > 0)
                {
                    int prescriptionid = prescriptionBL.addPrescription(prescription);
                    if (prescriptionid > 0)
                    {

                        for (int i = 0; i < tableViewToaThuocMau_Thuoc.DataRowCount; i++)
                        {
                            int maThuoc = 0;
                            int sang = 0;
                            int trua = 0;
                            int chieu = 0;
                            int toi = 0;
                            int soLuong = 0;
                            string cachDung = "";
                            try
                            {
                                maThuoc = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["tenThuoc"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                sang = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["sang"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                trua = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["trua"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                chieu = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["chieu"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                toi = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["toi"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                soLuong = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["soLuong"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                cachDung = tableViewToaThuocMau_Thuoc.GetDataRow(i)["cachDung"].ToString();
                            }
                            catch { }

                            PrescriptionDetail prescriptionDetail = prescriptionBL.createPrescritionDetail();
                            prescriptionDetail.setPrescriptionId(prescriptionid);
                            prescriptionDetail.setMedicineId(maThuoc);
                            prescriptionDetail.setMorningMed(sang);
                            prescriptionDetail.setNoonMed(trua);
                            prescriptionDetail.setAfternoonMed(chieu);
                            prescriptionDetail.setEveningMed(toi);
                            prescriptionDetail.setQuantity(soLuong);
                            prescriptionDetail.setDosage(cachDung);

                            bool success = prescriptionBL.addPrescriptionDetail(prescriptionDetail);
                            if (success == false)
                            {
                                message.title = "Toa Mẫu";
                                message.Content = "Xảy ra lỗi trong quá trình lưu toa mẫu.";
                                message.ShowDialog();
                                return;
                            }
                        }
                        message.title = "Toa Mẫu";
                        message.Content = "Lưu toa mẫu thành công.";
                        message.ShowDialog();
                        btnToaMau_LuuToaMau.Enabled = false;
                    }
                    else
                    {
                        message.title = "Toa Mẫu";
                        message.Content = "Lưu toa mẫu thất bại. Vui lòng kiểm tra lại.";
                        message.ShowDialog();
                    }
                }
                else
                {
                    message.title = "Toa Mẫu";
                    message.Content = "Chưa khai báo thuốc cho toa mẫu.";
                    message.ShowDialog();
                }
            }
            initTabToaMau();

        }
        //Cập nhật toa mẫu
        private void btnToaMau_CapNhat_Click(object sender, EventArgs e)
        {
            int maToaMau = 0;
            try
            {
                maToaMau = Convert.ToInt32(txtToaMau_MaSo.Text);
            }
            catch (Exception) { }
            string tenToaMau = txtToaMau_TenToa.Text;
            string moTa = txtToaMau_MoTa.Text;

            if (tenToaMau == "")
            {
                message.title = "Toa Mẫu";
                message.Content = "Chưa nhập tên toa mẫu";
                message.ShowDialog();
            }
            else
            {
                Prescription prescription = prescriptionBL.createPrescrition();
                prescription.setPrescriptionId(maToaMau);
                prescription.setPrescriptionName(tenToaMau);
                prescription.setPrescriptionNote(moTa);
                int row = tableViewToaThuocMau_Thuoc.DataRowCount;
                if (row > 0)
                {
                    if (prescriptionBL.updatePrescription(prescription))
                    {
                        //Xóa chi tiết toa mẫu trước khi cập nhật
                        string sqlDeletePrescriptionDetail = "delete from PRESCRIPTIONFORMDETAIL where prescriptionid =" + maToaMau;
                        if (myQueryBL.doNonQuery(sqlDeletePrescriptionDetail))
                        {
                            for (int i = 0; i < tableViewToaThuocMau_Thuoc.DataRowCount; i++)
                            {
                                int maThuoc = 0;
                                int sang = 0;
                                int trua = 0;
                                int chieu = 0;
                                int toi = 0;
                                int soLuong = 0;
                                string cachDung = "";
                                try
                                {
                                    maThuoc = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["tenThuoc"].ToString());
                                }
                                catch (Exception) { }

                                try
                                {
                                    sang = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["sang"].ToString());
                                }
                                catch (Exception) { }

                                try
                                {
                                    trua = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["trua"].ToString());
                                }
                                catch (Exception) { }

                                try
                                {
                                    chieu = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["chieu"].ToString());
                                }
                                catch (Exception) { }

                                try
                                {
                                    toi = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["toi"].ToString());
                                }
                                catch (Exception) { }

                                try
                                {
                                    soLuong = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetDataRow(i)["soLuong"].ToString());
                                }
                                catch (Exception) { }

                                try
                                {
                                    cachDung = tableViewToaThuocMau_Thuoc.GetDataRow(i)["cachDung"].ToString();
                                }
                                catch { }

                                PrescriptionDetail prescriptionDetail = prescriptionBL.createPrescritionDetail();
                                prescriptionDetail.setPrescriptionId(maToaMau);
                                prescriptionDetail.setMedicineId(maThuoc);
                                prescriptionDetail.setMorningMed(sang);
                                prescriptionDetail.setNoonMed(trua);
                                prescriptionDetail.setAfternoonMed(chieu);
                                prescriptionDetail.setEveningMed(toi);
                                prescriptionDetail.setQuantity(soLuong);
                                prescriptionDetail.setDosage(cachDung);

                                bool success = prescriptionBL.addPrescriptionDetail(prescriptionDetail);
                                if (success == false)
                                {
                                    message.title = "Toa Mẫu";
                                    message.Content = "Xảy ra lỗi trong quá trình cập nhật toa mẫu.";
                                    message.ShowDialog();
                                    return;
                                }
                            }
                            message.title = "Toa Mẫu";
                            message.Content = "Cập nhật toa mẫu thành công.";
                            message.ShowDialog();
                        }
                        else
                        {
                            message.title = "Toa Mẫu";
                            message.Content = "Xảy ra lỗi trong quá trình cập nhật toa mẫu.";
                            message.ShowDialog();
                        }


                    }
                    else
                    {
                        message.title = "Toa Mẫu";
                        message.Content = "Cập nhật toa mẫu thất bại. Vui lòng kiểm tra lại kết nói server";
                        message.ShowDialog();
                    }
                }
                else
                {
                    message.title = "Toa Mẫu";
                    message.Content = "Toa mẫu phải có khai báo thuốc, nếu không có thể xóa toa mẫu.";
                    message.ShowDialog();
                }

            }
        }
        //Xóa toa mẫu
        private void btnToaMau_XoaToaMau_Click(object sender, EventArgs e)
        {
            int maSo = 0;
            maSo = Convert.ToInt32(txtToaMau_MaSo.Text);
            if (maSo == 0)
            {
                message.title = "Toa Mẫu";
                message.Content = "Chưa chọn toa mẫu cần xóa.";
                message.ShowDialog();
            }
            else
            {
                string sqlDeletePrescription = "delete from PRESCRIPTIONFORM where prescriptionid =" + maSo;
                string sqlDeletePrescriptionDetail = "delete from PRESCRIPTIONFORMDETAIL where prescriptionid =" + maSo;
                if (myQueryBL.doNonQuery(sqlDeletePrescriptionDetail) && myQueryBL.doNonQuery(sqlDeletePrescription))
                {
                    message.title = "Toa Mẫu";
                    message.Content = "Xóa toa mẫu thành công.";
                    message.ShowDialog();
                    btnToaMau_ToaMauMoi_Click(sender, e);
                    initTabToaMau();
                    btnToaMau_CapNhat.Enabled = false;
                    btnToaMau_XoaToaMau.Enabled = false;
                }
                else
                {
                    message.title = "Toa Mẫu";
                    message.Content = "Xóa toa mẫu không thành công. Vui lòng kiểm tra lại kết nối server";
                    message.ShowDialog();
                }

            }
            initTabToaMau();
        }

        private void cbbHoSoBenhAn_ToaThuocMau_EditValueChanged(object sender, EventArgs e)
        {

        }
        private void tableViewToaThuocMau_Thuoc_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            tableViewToaThuocMau_Thuoc.SetRowCellValue(e.RowHandle, tableViewToaThuocMau_Thuoc.Columns[1], 0);
            tableViewToaThuocMau_Thuoc.SetRowCellValue(e.RowHandle, tableViewToaThuocMau_Thuoc.Columns[2], 0);
            tableViewToaThuocMau_Thuoc.SetRowCellValue(e.RowHandle, tableViewToaThuocMau_Thuoc.Columns[3], 0);
            tableViewToaThuocMau_Thuoc.SetRowCellValue(e.RowHandle, tableViewToaThuocMau_Thuoc.Columns[4], 0);
            tableViewToaThuocMau_Thuoc.SetRowCellValue(e.RowHandle, tableViewToaThuocMau_Thuoc.Columns[5], 0);


        }

        private void tableViewToaThuocMau_Thuoc_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
        }

        private void tableViewToaThuocMau_Thuoc_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {


        }

        private void tableViewToaThuocMau_Thuoc_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {


        }

        //sự kiện click chuột sự hồ sơ bệnh án - lịch sử khám bệnh
        private void tableHoSoBenhAn_LichSuKhamBenh_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                txtHoSoBenhAn_MaSo.Text = tableViewHoSoBenhAn_LichSuKhamBenh.GetFocusedDataRow()["patientid"].ToString();
                txtHoSoBenhAn_HoTen.Text = tableViewHoSoBenhAn_LichSuKhamBenh.GetFocusedDataRow()["fullname"].ToString();
                cbbHoSoBenhAn_GioiTinh.Text = tableViewHoSoBenhAn_LichSuKhamBenh.GetFocusedDataRow()["sex"].ToString();
            }
            catch (Exception)
            {

            }
        }
        // Sự kiện Hồ sơ bệnh án - Lưu toa thuốc
        private void btnHoSoBenhAn_Luu_Click(object sender, EventArgs e)
        {
            string trieuChung = "";
            int chuanDoan = 0;
            string loiDan = "";
            int ngayThuoc = 0;
            try
            {
                trieuChung = cbbHoSoBenhAn_TrieuChung.Text;
            }
            catch (Exception) { }

            try
            {
                chuanDoan = Convert.ToInt32(cbbHoSoBenhAn_ChuanDoan.EditValue.ToString());
            }
            catch (Exception) { }

            try
            {
                loiDan = cbbHoSoBenhAn_LoiDan.Text;
            }
            catch (Exception) { }

            try
            {
                ngayThuoc = Convert.ToInt32(txtHoSoBenhAn_NgayThuoc.Text);
            }
            catch (Exception) { }

            //xử lý
            if (trieuChung == "")
            {
                message.title = "Hồ sơ bệnh án";
                message.Content = "Hệ thống yêu cầu phải nhập triệu chứng của bệnh nhân";
                message.ShowDialog();
            }
            else if (chuanDoan == 0)
            {
                message.title = "Hồ sơ bệnh án";
                message.Content = "Hệ thống yêu cầu phải nhập chuẩn đoán bệnh cho bệnh nhân";
                message.ShowDialog();
            }
            else if (ngayThuoc == 0)
            {
                message.title = "Hồ sơ bệnh án";
                message.Content = "Hệ thống yêu cầu phải nhập số ngày thuốc lớn hơn không (0)";
                message.ShowDialog();
            }
            else
            {
                if (tableViewHoSoBenhAn_Thuoc.DataRowCount == 0)
                {
                    message.title = "Hồ sơ bệnh án";
                    message.Content = "Hệ thống yêu cầu phải cung cấp đơn thuốc cho bệnh nhân";
                    message.ShowDialog();
                }
                else
                {
                    int maKhamBenh = 0;
                    try
                    {
                        maKhamBenh = Convert.ToInt32(tableViewHoSoBenhAn_DanhSachKhamBenh.GetFocusedDataRow()["treatmentid"].ToString());
                    }
                    catch (Exception) { }

                    string sqlTaiKham = "";
                    string sqlUpdateTreatment = "update treatment set treatmentstatusid = 3, symptom =N'" + trieuChung + "', diagnosisid =" + chuanDoan + ", advice =N'" + loiDan + "', dayofusingmedicine =" + ngayThuoc + " where treatmentid=" + maKhamBenh;
                    if (myQueryBL.doNonQuery(sqlUpdateTreatment))
                    {
                        for (int i = 0; i < tableViewHoSoBenhAn_Thuoc.DataRowCount; i++)
                        {
                            int maThuoc = 0;
                            int sang = 0;
                            int trua = 0;
                            int chieu = 0;
                            int toi = 0;
                            int soLuong = 0;
                            string cachDung = "";
                            try
                            {
                                maThuoc = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetDataRow(i)["tenThuoc"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                sang = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetDataRow(i)["sang"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                trua = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetDataRow(i)["trua"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                chieu = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetDataRow(i)["chieu"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                toi = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetDataRow(i)["toi"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                soLuong = Convert.ToInt32(tableViewHoSoBenhAn_Thuoc.GetDataRow(i)["soLuong"].ToString());
                            }
                            catch (Exception) { }

                            try
                            {
                                cachDung = tableViewHoSoBenhAn_Thuoc.GetRowCellDisplayText(i, "cachDung").ToString();
                            }
                            catch { }

                            TreatmentDetail detail = treatmentBL.createTreatmentDetail();
                            detail.setTreatmentId(maKhamBenh);
                            detail.setMedicinetId(maThuoc);
                            detail.setMorningMed(sang);
                            detail.setNoonMed(trua);
                            detail.setAfternoonMed(chieu);
                            detail.setEveningMed(toi);
                            detail.setQuantity(soLuong);
                            detail.setDosage(cachDung);
                            treatmentBL.addTreatmentDetail(detail);

                            
                        }
                        message.title = "Thông tin khám bệnh";
                        message.Content = "Lưu thông tin khám bệnh thành công.";
                        message.ShowDialog();
                        btnHoSoBenhAn_Luu.Enabled = false;

                        //get lịch sử khám bệnh
                        int patientid = 0;
                        try
                        {
                            patientid = Convert.ToInt32(txtHoSoBenhAn_MaSo.Text);
                        }
                        catch (Exception) { }

                        string sqlTreatmentHistory = "select treatmentid, dateoftreatment, diagnosisname from ((treatment inner join patient on treatment.patientid = patient.patientid) inner join diagnosis on diagnosis.diagnosisid = treatment.diagnosisid) where patient.patientid=" + patientid + " order by dateoftreatment asc";
                        string[] strTreatmentHistory = myQueryBL.doQuery(sqlTreatmentHistory);
                        tableHoSoBenhAn_LichSuKhamBenh.DataSource = Kb.getTreatmentHistory(strTreatmentHistory);
                    }
                    else
                    {
                        message.title = "Thông tin khám bệnh";
                        message.Content = "Lưu thông tin khám bệnh không thành công. Vui lòng kiểm tra lại.";
                        message.ShowDialog();
                    }
                }

            }

        }
        //Danh sách toa mẫu
        private void tableToaThuocMau_DanhSach_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                txtToaMau_MaSo.Text = tableViewToaThuocMau_DanhSach.GetFocusedDataRow()["maSo"].ToString();
                txtToaMau_TenToa.Text = tableViewToaThuocMau_DanhSach.GetFocusedDataRow()["tenToa"].ToString();
                txtToaMau_MoTa.Text = tableViewToaThuocMau_DanhSach.GetFocusedDataRow()["moTa"].ToString();
                int maSo = 0;
                try
                {
                    maSo = Convert.ToInt32(txtToaMau_MaSo.Text);
                }
                catch (Exception) { }
                tableViewToaThuocMau_Thuoc.GridControl.DataSource = Kb.getPrescriptionFormById(myQueryBL, maSo);
                if (tableViewToaThuocMau_Thuoc.DataRowCount == 0)
                {
                    message.title = "Thông tin toa mẫu";
                    message.Content = "Toa mẫu không có dữ liệu thuốc. Vui lòng thêm dữ liệu thuốc vào.";
                    message.ShowDialog();
                }
                else
                {
                    for (int i = 0; i < tableViewToaThuocMau_Thuoc.DataRowCount; i++)
                    {
                        int maThuoc = 0;

                        try
                        {
                            maThuoc = Convert.ToInt32(tableViewToaThuocMau_Thuoc.GetRowCellValue(i, "maThuoc"));
                        }
                        catch (Exception) { }
                        tableViewToaThuocMau_Thuoc.SetRowCellValue(i, tableViewToaThuocMau_Thuoc.Columns[0], maThuoc);
                    }
                }

                if (txtToaMau_MaSo.Text != "")
                {
                    btnToaMau_CapNhat.Enabled = true;
                    btnToaMau_XoaToaMau.Enabled = true;
                    btnToaMau_LuuToaMau.Enabled = false;
                }
            }
            catch (Exception)
            {

            }
        }
        //Tìm kiếm bệnh nhân thanh toán
        private void btnThanhToan_TimKiem_Click(object sender, EventArgs e)
        {
            //Format datetime
            dateThanhToan_TkNgayKham.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            dateThanhToan_TkNgayKham.Properties.DisplayFormat.FormatString = "dd/MM/yyyy";
            int maSo = 0;
            try
            {
                maSo = Convert.ToInt32(txtThanhToan_TkMaSo.Text);
            }
            catch (Exception) { }
            string hoTen = txtThanhToan_TkHoTen.Text;
            string namSinh = txtThanhToan_TkNamSinh.Text;
            int gioiTinh = cbbThanhToan_TkGioiTinh.SelectedIndex;
            string soCMND = txtThanhToan_TkSoCMND.Text;
            string ngayKham = dateThanhToan_TkNgayKham.Text;
            int tinhTrang = cbbThanhToan_TkTinhTrang.SelectedIndex;

            if (maSo == 0 && hoTen == "" && namSinh == "" && gioiTinh == 0 && soCMND == "" && ngayKham == "" && tinhTrang == 0)
            {
                message.Content = "Chưa nhập nội dung tìm kiếm";
                message.title = "Thông báo tìm kiếm";
                message.ShowDialog();
            }
            else
            {
                splashScreenManager.ShowWaitForm();
                tableViewThanhToan_DanhSach.GridControl.DataSource = Kb.getPatientListPayment(myQueryBL, maSo, hoTen, namSinh, gioiTinh, soCMND, ngayKham, tinhTrang);
                cbbThanhToan_KieuThanhToan.Text = "";
                splashScreenManager.CloseWaitForm();

            }
        }
        //mouse click thanh toán bệnh nhân
        string tienThuocUong = "";
        string tongTien = "";
        private void tableThanhToan_DanhSach_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                txtThanhToan_MaSo.Text = tableViewThanhToan_DanhSach.GetFocusedDataRow()["treatmentid"].ToString();
                txtThanhToan_HoTen.Text = tableViewThanhToan_DanhSach.GetFocusedDataRow()["fullname"].ToString();
                cbbThanhToan_GioiTinh.Text = tableViewThanhToan_DanhSach.GetFocusedDataRow()["sex"].ToString();
                txtThanhToan_NgaySinh.Text = tableViewThanhToan_DanhSach.GetFocusedDataRow()["dateofbirth"].ToString();
                txtThanhToan_DiaChi.Text = tableViewThanhToan_DanhSach.GetFocusedDataRow()["address"].ToString();
                txtThanhToan_SoCMND.Text = tableViewThanhToan_DanhSach.GetFocusedDataRow()["idcard"].ToString();
                if (Convert.ToInt32(tableViewThanhToan_DanhSach.GetFocusedDataRow()["paystatusid"].ToString()) == 1)
                {
                    btnThanhToan_ThanhToan.Enabled = false;
                    btnThanhToan_InHoaDon.Enabled = false;
                }
                else
                {
                    btnThanhToan_ThanhToan.Enabled = true;
                    btnThanhToan_InHoaDon.Enabled = true;
                }


                if (txtThanhToan_MaSo.Text != "")
                {
                    int maSo = 0;
                    try
                    {
                        maSo = Convert.ToInt32(txtThanhToan_MaSo.Text);
                    }
                    catch (Exception) { }

                    tableViewThanhToan_ThongTinThuoc.GridControl.DataSource = Kb.getListMedicineByTreatmentId(myQueryBL, maSo);
                    int tienThuoc = 0;
                    for (int i = 0; i < tableViewThanhToan_ThongTinThuoc.DataRowCount; i++)
                    {
                        int maThuoc = 0;
                        int soLuong = 0;
                        int donGia = 0;
                        try
                        {
                            maThuoc = Convert.ToInt32(tableViewThanhToan_ThongTinThuoc.GetRowCellValue(i, "medicineid"));
                        }
                        catch (Exception) { }
                        try
                        {
                            soLuong = Convert.ToInt32(tableViewThanhToan_ThongTinThuoc.GetRowCellValue(i, "quantitytotal"));
                        }
                        catch (Exception) { }

                        string query = "select  medicinedetailid, cost from MEDICINEDETAIL where medicineid = " + maThuoc +
                            " and expirationdate > GETDATE() and expirationdate <= all(select expirationdate from MEDICINEDETAIL where medicineid =" + maThuoc + ")" +
                            " and (remainingquantity > " + soLuong + " and remainingquantity <=all(select remainingquantity from MEDICINEDETAIL where medicineid = " + maThuoc + "))";
                        string[] str = myQueryBL.doQuery(query);
                        donGia = Kb.DonGiaThuocThanhToan(str);
                        tableViewThanhToan_ThongTinThuoc.SetRowCellValue(i, tableViewThanhToan_ThongTinThuoc.Columns["cost"], donGia);
                        tableViewThanhToan_ThongTinThuoc.SetRowCellValue(i, tableViewThanhToan_ThongTinThuoc.Columns["money"], donGia * soLuong);
                        tienThuoc = tienThuoc + soLuong * donGia;
                    }
                    lbThanhToan_TienThuoc.Text = tienThuoc.ToString();
                    //get Tiền khám
                    int tienKham = 0;
                    string sqlTienkham = "select treatmentcost from param";
                    string[] strTienKham = myQueryBL.doQuery(sqlTienkham);
                    tienKham = Kb.TienKham(strTienKham);
                    lbThanhToan_TienKham.Text = tienKham.ToString();
                    lbThanhToan_TongTien.Text = (tienKham + tienThuoc).ToString();

                    tienThuocUong = tienThuoc.ToString();
                    tongTien = lbThanhToan_TongTien.Text;
                }
            }
            catch (Exception) { }

        }
        //sự kiện thay đổi kiểu danh sách thanh toán
        private void cbbThanhToan_KieuThanhToan_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbThanhToan_KieuThanhToan.Text != null)
            {
                int index = cbbThanhToan_KieuThanhToan.SelectedIndex;
                DateTime time = DateTime.Now;

                if (index == 0)
                {
                    tableViewThanhToan_DanhSach.GridControl.DataSource = Kb.getPatientListPayment(myQueryBL, 0, "", "", 0, "", "today", 1);
                }
                else if (index == 1)
                {
                    tableViewThanhToan_DanhSach.GridControl.DataSource = Kb.getPatientListPayment(myQueryBL, 0, "", "", 0, "", "today", 2);
                }

            }
        }
        //Thanh toán hóa đơn bệnh nhân
        private void btnThanhToan_ThanhToan_Click(object sender, EventArgs e)
        {
            int tienKham = 0;
            int tienThuoc = 0;
            int tongTien = 0;
            int maKhamBenh = 0;
            tienKham = Convert.ToInt32(lbThanhToan_TienKham.Text);
            maKhamBenh = Convert.ToInt32(txtThanhToan_MaSo.Text);
            //có sử dụng thuốc
            if (ckbThanhToan_KhongSuDungThuoc.Checked == true)
            {
                tienThuoc = Convert.ToInt32(lbThanhToan_TienThuoc.Text);
                tongTien = Convert.ToInt32(lbThanhToan_TongTien.Text);
                string query = "update TREATMENT set treatmentcost =" + tienKham + ", medicinecost = " + tienThuoc + ", paystatus = 1 where treatmentid =" + maKhamBenh;
                if (myQueryBL.doNonQuery(query))
                {

                    for (int i = 0; i < tableViewThanhToan_ThongTinThuoc.DataRowCount; i++)
                    {
                        int money = 0;
                        int medicineid = 0;
                        money = Convert.ToInt32(tableViewThanhToan_ThongTinThuoc.GetRowCellValue(i, "money"));
                        medicineid = Convert.ToInt32(tableViewThanhToan_ThongTinThuoc.GetRowCellValue(i, "medicineid"));
                        string queryTreatmentDetail = "update TREATMENTDETAIL set money = " + money + " where treatmentid =" + maKhamBenh + " and medicineid = " + medicineid;
                        if (!myQueryBL.doNonQuery(queryTreatmentDetail))
                        {
                            message.title = "Thông báo";
                            message.Content = "Cập nhật thanh toán cho bệnh nhân không thanh công. Vui lòng thực hiện lại";
                            message.ShowDialog();
                            return;
                        }

                    }
                    message.title = "Thông báo";
                    message.Content = "Cập nhật thanh toán cho bệnh nhân thành công.";
                    message.ShowDialog();
                    btnThanhToan_ThanhToan.Enabled = false;
                    initThanhToan();
                }


            }
            else
            {

            }
        }
        // In hóa đơn thanh toán bệnh nhân
        private void btnThanhToan_InHoaDon_Click(object sender, EventArgs e)
        {

        }
        //báo cáo doanh thu
        private void btnDoanhThu_BaoCao_Click(object sender, EventArgs e)
        {
            dateDoanhThu_TuNgay.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            dateDoanhThu_TuNgay.Properties.DisplayFormat.FormatString = "dd/MM/yyyy";
            dateDoanhThu_DenNgay.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            dateDoanhThu_DenNgay.Properties.DisplayFormat.FormatString = "dd/MM/yyyy";

            string tuNgay = dateDoanhThu_TuNgay.EditValue.ToString();
            string denNgay = dateDoanhThu_DenNgay.EditValue.ToString();

            int num = 0;
            for (DateTime date = DateTime.Now; date < (DateTime)dateDoanhThu_DenNgay.EditValue; date = date.AddDays(1.0))
            {
                num++;
                seriesDoanhThu.Points.Add(new SeriesPoint(date, new double[] {num}));
            }

            
        }

        private void ckbThanhToan_KhongSuDungThuoc_CheckedChanged(object sender, EventArgs e)
        {

            if (ckbThanhToan_KhongSuDungThuoc.Checked == false)
            {
                lbThanhToan_TienThuoc.Text = "0";
                lbThanhToan_TongTien.Text = lbThanhToan_TienKham.Text;
            }
            else
            {
                lbThanhToan_TienThuoc.Text = tienThuocUong;
                lbThanhToan_TongTien.Text = tongTien;
            }
        }

        private void txtHoSoBenhAn_TkCMND_EditValueChanged(object sender, EventArgs e)
        {

        }



    }
}